package com.dlc.laboratory.ui.things

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.widget.Toast
import com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.databinding.ActivitySelectAuthMethodBinding
import com.dlc.eboard.mqtt.MqttManager
import com.dlc.eboard.serial.OnSerialScanListener
import com.dlc.eboard.serial.SerialPortHelper
import com.dlc.eboard.ui.auth.fragment.CardAuthFragment
import com.dlc.eboard.ui.common.BaseCountDownActivity
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.rc.httpcore.client.ApiRepository
import java.lang.ref.WeakReference

/**
 * info
 *
 * @author ReiChin_
 */
class SelectAuthMethodActivity :
    BaseCountDownActivity<ActivitySelectAuthMethodBinding>() {
    private val weakHandler by lazy {  WeakReferenceHandler(this) }
    override fun createViewBinding() = ActivitySelectAuthMethodBinding.inflate(layoutInflater)

    override val mTitleBar: TitleBar by lazy { viewBinding.titleBar }
    override val mNavView: NavViewCompat by lazy { viewBinding.navView }

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)

        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(
            R.id.container,
            CardAuthFragment.newInstance(),
            CardAuthFragment.TAG
        )
        transaction.commitAllowingStateLoss()

        if (Constants.Mock.SCHOOL_NUM_TEST) {
//            object : Handler(Looper.getMainLooper()) {
//
//                override fun handleMessage(msg: Message) {
//                    lotInCheck(Constants.Mock.SCHOOL_NUM)
//                }
//            }
            weakHandler.sendEmptyMessageDelayed(1, 1500)
        }
    }

    override fun onResume() {
        mSerialPortHelper.onResume()
        super.onResume()
    }

    override fun onPause() {
        mSerialPortHelper.onPause()
        super.onPause()
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        mSerialPortHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

    private val mSerialPortHelper by lazy {
        SerialPortHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                lotInCheck(content)
            }
        })
    }

    private fun lotInCheck(username: String) {
        if (null == LabApp.sLabConfig) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return
        }

        showLoading("查询中....")
        val disposable = ApiRepository.lotInCheck(LabApp.sLabConfig!!.labId, username)
            .subscribe({
                dismissLoading()
                val intent = Intent(this, ExThingsActivity::class.java)
                intent.putExtra("nickName", it)
                startActivity(intent)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    override fun enabledBackCountDown() = true

    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: SelectAuthMethodActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<SelectAuthMethodActivity> = WeakReference(obj)

        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                lotInCheck(Constants.Mock.SCHOOL_NUM)
            }
        }
    }

    override fun onDestroy() {
        weakHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }
}