package com.grkj.iscs.view.dialog

import android.content.Context
import com.clj.fastble.BleManager
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.grkj.iscs.view.base.BaseDialog
import com.grkj.iscs.ble.BleCmdManager
import com.grkj.iscs.ble.BleConst.STATUS_READY
import com.grkj.iscs.ble.CustomBleWriteCallback
import com.grkj.iscs.databinding.DialogKeyReturnConfirmBinding
import com.grkj.iscs.util.log.LogUtil

/**
 * 钥匙归还工作票未完成提示弹框
 */
class KeyReturnConfirmDialog(ctx: Context): BaseDialog<DialogKeyReturnConfirmBinding>(ctx) {

    private var bleDevice: BleDevice? = null

    override val viewBinding: DialogKeyReturnConfirmBinding
        get() = DialogKeyReturnConfirmBinding.inflate(layoutInflater)

    override fun initView() {
        mBinding?.tvCancel?.setOnClickListener {
            // TODO 打开钥匙卡扣、断开连接
            dismiss()
        }

        mBinding?.tvConfirm?.setOnClickListener {
            // TODO 设置待机模式、断开连接
            dismiss()
        }
    }

    fun setDataAndShow(bleDevice: BleDevice) {
        this.bleDevice = bleDevice
        show()
    }

    fun setKeyModeReady() {
        BleCmdManager.switchMode(STATUS_READY, bleDevice!!, object : CustomBleWriteCallback() {
            override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                LogUtil.i("switch mode ready success")}
            override fun onWriteFailure(exception: BleException?) {
                LogUtil.e("switch mode ready fail")}
        })
    }

    override fun dismiss() {
        super.dismiss()
        bleDevice?.let {
            BleManager.getInstance().disconnect(it)
            bleDevice = null
        }
    }
}