package com.casic.br.view.device

import android.os.Handler
import android.util.Log
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.adapter.MotionLogAdapter
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.selectCategory
import com.casic.br.extensions.toBatteryImage
import com.casic.br.utils.DeserializeModel
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.timestampToTime
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.home.sdk.bean.HomeBean
import com.tuya.smart.home.sdk.callback.ITuyaHomeResultCallback
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.activity_motion_senser.*
import kotlinx.android.synthetic.main.include_device_title.*
import java.util.*

/**
 * 运动传感器
 * TODO 数据上报暂缓
 * */
class MotionSensorActivity : KotlinBaseActivity() {

    private val kTag = "MotionSensorActivity"
    private val context = this@MotionSensorActivity
    private val dataTimer by lazy { Timer() }//数据上传Timer
    private val timeLinkedList = LinkedList<String>()
    private lateinit var weakReference: WeakReferenceHandler
    private lateinit var motionAdapter: MotionLogAdapter
    private var dataBeans: MutableList<String> = ArrayList()

    override fun initLayoutView(): Int = R.layout.activity_motion_senser

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        initLayoutImmersionBar(rootView)
        ImmersionBar.with(this).statusBarDarkFont(true).init()

        leftBackView.setOnClickListener { finish() }
        rightOperateView.visibility = View.GONE
    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)
        motionAdapter = MotionLogAdapter(this, dataBeans)
        motionRecyclerView.adapter = motionAdapter
        //每隔5s传一次数据到服务器
        dataTimer.schedule(object : TimerTask() {
            override fun run() {
                TuyaHomeSdk.newHomeInstance(DeserializeModel.getHomeId())
                    .getHomeDetail(object : ITuyaHomeResultCallback {
                        override fun onSuccess(bean: HomeBean) {
                            bean.deviceList.forEach {
                                val selectedCategory = it.selectCategory()
                                if (selectedCategory == "0204") {
                                    //人体传感器
                                    val msg = weakReference.obtainMessage()
                                    msg.what = 2022102001
                                    msg.obj = it
                                    weakReference.sendMessage(msg)
                                }
                            }
                        }

                        override fun onError(errorCode: String, errorMsg: String) {
                            Log.d(kTag, "onError: $errorMsg")
                        }
                    })
            }
        }, 0, 5000)
    }

    private val callback = Handler.Callback { message ->
        if (message.what == 2022102001) {
            if (!this.isDestroyed) {
                val it = message.obj as DeviceBean
                deviceStateView.text = if (it.isOnline) {
                    "设备在线"
                } else {
                    "设备已离线"
                }
                titleView.text = it.name
                Glide.with(this)
                    .load(it.iconUrl)
                    .apply(RequestOptions.circleCropTransform())
                    .placeholder(R.mipmap.load_image_error)
                    .into(deviceLogoView)

                val value = it.dps["103"].toString()
                batteryView.setBackgroundResource(value.toBatteryImage())
                batteryValueView.text = "${value}%"

                if (it.dps["101"] as Boolean) {
                    val time = (it.dpsTime["101"].toString().toLong()).timestampToTime()
                    timeLinkedList.add(time)
                    //需要判断当前最后一次时间喝上一次事件是否相同，相同就跳过
                    if (timeLinkedList.size == 1) {
                        dataBeans.add(timeLinkedList.last)
                    } else if (timeLinkedList.last != timeLinkedList[timeLinkedList.size - 2]) {
                        dataBeans.add(timeLinkedList.last)
                    }
                    motionAdapter.notifyDataSetChanged()
                } else {
                    Log.d(kTag, "未检测到人体数据")
                }
            }
        }
        true
    }

    override fun initEvent() {

    }

    override fun onDestroy() {
        super.onDestroy()
        dataTimer.cancel()
    }
}