package com.casic.br.view

import android.os.CountDownTimer
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.amap.api.location.AMapLocation
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.base.BaseApplication
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.utils.LocationHelper
import com.casic.br.vm.DeviceViewModel
import com.casic.br.widgets.WaterRippleView
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.pengxh.kt.lite.vm.LoadState
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.home.sdk.builder.TuyaGwSubDevActivatorBuilder
import com.tuya.smart.sdk.api.ITuyaActivator
import com.tuya.smart.sdk.api.ITuyaSmartActivatorListener
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.activity_gateway.*
import kotlinx.android.synthetic.main.activity_scan_zigbee.*
import kotlinx.android.synthetic.main.activity_scan_zigbee.deviceLogoView
import kotlinx.android.synthetic.main.activity_scan_zigbee.rootView
import kotlinx.android.synthetic.main.include_base_title.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class ScanZigbeeActivity : KotlinBaseActivity() {

    private val kTag = "ScanZigbeeActivity"
    private var isRunning = true
    private lateinit var singleThreadExecutor: ExecutorService
    private lateinit var deviceId: String
    private lateinit var deviceViewModel: DeviceViewModel
    private lateinit var subDevActivator: ITuyaActivator
    private lateinit var weakReferenceHandler: WeakReferenceHandler
    private lateinit var deviceBean: DeviceBean
    private lateinit var location: AMapLocation

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

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        initLayoutImmersionBar(rootView)
        leftBackView.setOnClickListener { finish() }
        titleView.text = String.format("搜索Zigbee设备")
    }

    override fun observeRequestState() {
        deviceViewModel.loadState.observe(this, {
            when (it) {
                LoadState.Success -> {
                    LoadingDialogHub.dismiss()
                    navigatePageTo<AddDeviceResultActivity>()
                }
                else -> {
                    "添加失败，请重新绑定".show(this)
                    LoadingDialogHub.dismiss()
                }
            }
        })
    }

    override fun initData() {
        //只有一个核心线程，当被占用时，其他的任务需要进入队列等待
        singleThreadExecutor = Executors.newSingleThreadExecutor()
        waterRippleView.setOnAnimationStartListener(object :
            WaterRippleView.OnAnimationStartListener {
            override fun onStart(view: WaterRippleView?) {
                view?.start()
                //开启线程搜索设备
                Log.d(kTag, "onStart: 开始线程")
                singleThreadExecutor.execute(searchRunnable)
                isRunning = true
            }
        })

        deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        deviceViewModel = ViewModelProvider(this)[DeviceViewModel::class.java]
        weakReferenceHandler = WeakReferenceHandler(callback)

        LocationHelper.obtainCurrentLocation(this, object : LocationHelper.ILocationListener {
            override fun onAMapLocationGet(aMapLocation: AMapLocation?) {
                if (aMapLocation == null) {
                    "信号弱，添加设备失败".show(BaseApplication.obtainInstance())
                    LoadingDialogHub.dismiss()
                    return
                }
                location = aMapLocation
                val configBuilder = TuyaGwSubDevActivatorBuilder().setDevId(deviceId)
                    .setListener(object : ITuyaSmartActivatorListener {
                        override fun onError(errorCode: String?, errorMsg: String?) {
                            Log.e(kTag, "onError: $errorMsg")
                        }

                        override fun onActiveSuccess(devResp: DeviceBean?) {
                            if (devResp == null) {
                                Log.e(kTag, "onActiveSuccess: 无法扫描到涂鸦Zigbee模组")
                                return
                            }
                            deviceBean = devResp
                            tipsView.text = String.format("已搜索到Zigbee设备，基本信息如下")
                            logoViewLayout.visibility = View.VISIBLE
                            Glide.with(this@ScanZigbeeActivity)
                                .load(deviceBean.iconUrl)
                                .apply(RequestOptions.circleCropTransform())
                                .placeholder(R.mipmap.load_image_error)
                                .into(deviceLogoView)
                            deviceNameView.text = String.format("产品名称：${deviceBean.name}")

                            //将绑定的设备存入自己的数据库
                            weakReferenceHandler.sendEmptyMessage(2022101902)
                        }

                        override fun onStep(step: String?, data: Any?) {

                        }
                    })
                subDevActivator =
                    TuyaHomeSdk.getActivatorInstance().newGwSubDevActivator(configBuilder)
                subDevActivator.start()
            }
        })
    }

    private val callback = Handler.Callback {
        if (it.what == 2022101902) {
            LoadingDialogHub.show(this, "设备绑定成功，开始同步服务器数据")
            object : CountDownTimer(5000, 1000) {
                override fun onTick(millisUntilFinished: Long) {

                }

                override fun onFinish() {
                    deviceViewModel.addDevice(
                        deviceBean,
                        DeserializeModel.getUserModel()!!,
                        "1",
                        location
                    )
                }
            }.start()
        }
        true
    }

    override fun initEvent() {

    }

    private val searchRunnable = Runnable {
        while (true) {
            try {
                if (!isRunning) {
                    Log.d(kTag, "run: 设备搜索线程休眠中...")
                    Thread.sleep(Long.MAX_VALUE)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            Log.d(kTag, "run: 设备搜索线程运行中...")
            try {
                //搜索设备
                Thread.sleep(1000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            subDevActivator.stop()
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        super.onPause()
        isRunning = false
        waterRippleView.stop()
        subDevActivator.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        subDevActivator.onDestroy()
    }
}