package com.casic.br.fragment.cooker

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Handler
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.diffDate
import com.casic.br.vm.DeviceViewModel
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.tuya.smart.sdk.api.ITuyaDevice
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.fragment_device_cooker_status.*
import java.util.*

class StatusPageFragment(private val deviceInstance: ITuyaDevice) : KotlinBaseFragment() {

    companion object {
        lateinit var weakReference: WeakReferenceHandler
    }

    private val kTag = "StatusPageFragment"
    private val wifi by lazy { requireContext().applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager }
    private val paramObject by lazy { org.json.JSONObject() }//数据Json对象
    private val dataTimer by lazy { Timer() }//数据上传Timer
    private lateinit var deviceViewModel: DeviceViewModel

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

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {

    }

    override fun initData() {
        weakReference = WeakReferenceHandler(callback)
        deviceViewModel = ViewModelProvider(this)[DeviceViewModel::class.java]
    }

    private val callback = Handler.Callback { message ->
        when (message.what) {
            2022092902 -> {
                val parseObject = JSONObject.parseObject(message.obj as String)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {//soft, low, medium, high
                            leftCookerStateView.text = when (parseObject[it] as String) {
                                "soft" -> "保温"
                                "low" -> "小火"
                                "medium" -> "中火"
                                "high" -> "猛火"
                                else -> "已关火"
                            }
                            paramObject.put("leftWorkStatus", leftCookerStateView.text)
                        }
                        "2" -> {//soft, low, medium, high
                            rightCookerStateView.text = when (parseObject[it] as String) {
                                "soft" -> "保温"
                                "low" -> "小火"
                                "medium" -> "中火"
                                "high" -> "猛火"
                                else -> "已关火"
                            }
                            paramObject.put("rightWorkStatus", rightCookerStateView.text)
                        }
                        "11" -> {
                            workingTimeView.text = String.format("${parseObject[it] as Int}min")
                            paramObject.put("runTime", workingTimeView.text)
                        }
                        "101" -> {
                            yzStatusSwitch.isChecked = parseObject[it] as Boolean
                            val smokeStove = if (yzStatusSwitch.isChecked) {
                                "1"
                            } else {
                                "0"
                            }
                            paramObject.put("smokeStove", smokeStove)
                        }
                    }
                }
            }
            2022092903 -> {
                val deviceBean = message.obj as DeviceBean
                deviceUsedTimeView.text = String.format("${deviceBean.time.toString().diffDate(false)}天")
                ipAddressView.text = deviceBean.ip

                paramObject.put("usageTime", deviceUsedTimeView.text)
                paramObject.put("deviceId", deviceBean.devId)
            }
        }
        true
    }

    override fun initEvent() {
        //每隔5s传一次数据到服务器
        dataTimer.schedule(object : TimerTask() {
            override fun run() {
                val obj = org.json.JSONObject()
                obj.put("gasStoveInfo", paramObject)
                deviceViewModel.addDeviceData(obj)
            }
        }, 0, 5000)
    }

    override fun onResume() {
        super.onResume()
        wifiStatusSwitch.isChecked = !wifi.connectionInfo.ssid.contains("unknown ssid")
        if (wifiStatusSwitch.isChecked) {
            wifiLayout.visibility = View.VISIBLE
            wifiNameView.text = wifi.connectionInfo.ssid.replace("\"", "")

            paramObject.put("wifiStatus", "ON")
            paramObject.put("wifiName", wifiNameView.text)
        } else {
            wifiLayout.visibility = View.GONE
            paramObject.put("wifiStatus", "OFF")
        }
    }

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