package com.abbidot.tracker.ui.activity.device

import android.content.Intent
import android.view.View
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivityAddNewTracker2Binding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.scan.BleScanRuleConfig
import com.clj.fastble.utils.HexUtil

class AddNewTracker2Activity :
    BaseActivity<ActivityAddNewTracker2Binding>(ActivityAddNewTracker2Binding::inflate) {

    private var isFirstBind = false
    private lateinit var mScanDeviceList: ArrayList<DataBean>

    //第一次没扫地设备，继续第二次
    private var againScan = true

    override fun getTopBar() = mViewBinding.ilAddNewTracker2TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_add_new_tracker)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
        }

        mScanDeviceList = ArrayList()

        mViewBinding.apply {
            lavAddNewTracker2Lottie.let {
                it.setAnimation("lottie/searching_tracker.json")
                it.postDelayed({
                    it.playAnimation()
                }, 500)
            }
        }

        Util.checkBluetoothPermissionsEnabled(this, {
            startScanBle()
        })
    }

    private fun startScanBle() {
        SRBleUtil.instance.cancelBleScan("AddNewTracker2Activity,已经在扫描蓝牙,取消蓝牙扫描")

        mScanDeviceList.clear()
        // 扫描超时时间，可选
        val scanRuleConfig = BleScanRuleConfig.Builder().setScanTimeOut(3000).build()
        BleManager.getInstance().initScanRule(scanRuleConfig)
        BleManager.getInstance().scan(object : BleScanCallback() {
            override fun onScanStarted(success: Boolean) {
                LogUtil.e("开始扫描...$success")
            }

            override fun onScanning(bleDevice: BleDevice?) {
                LogUtil.d("onScanning....$bleDevice")
                bleDevice?.apply {
                    if (null != name && name.contains(SRBleUtil.instance.trackDeviceBleStartName)) {
                        val start = 45
                        val end = start + 6
                        val subArray = scanRecord.sliceArray(start until end)
                        LogUtil.e("截取后的外显id广播=${HexUtil.formatHexString(subArray, true)}")
                        val deviceOutId = subArray.decodeToString()
                        DataBean().let {
                            it.name = deviceOutId
                            mScanDeviceList.add(it)
                        }
                    }
                }
            }

            override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                LogUtil.e("automaticConnection--扫描完成...${scanResultList?.size}")
                scanFinished()
            }
        })
    }

    private fun scanFinished() {
        if (againScan && mScanDeviceList.size == 0) {
            againScan = false
            LogUtil.e("没有扫描到设备，再次重试")
            startScanBle()
            return
        }
        if (mScanDeviceList.size > 0) {
            val intent = Intent(mContext, AddNewTracker3Activity::class.java)
            intent.putParcelableArrayListExtra(ConstantString.DeviceInfo, mScanDeviceList)
            intent.putExtra(ConstantString.isFirstBind, isFirstBind)
            startActivityFinish(intent)
        } else {
            mViewBinding.lavAddNewTracker2Lottie.visibility = View.GONE
            ViewUtil.instance.showDialog(
                mContext,
                R.string.txt_no_search_device,
                object : BaseDialog.OnDialogOkListener {
                    override fun onOkClick(dialog: BaseDialog<*>) {
                        dialog.dismiss()
                        againScan = true
                        mViewBinding.lavAddNewTracker2Lottie.visibility = View.VISIBLE
                        startScanBle()
                    }
                },
                okTextResId = R.string.txt_ok,
                cancelTextResId = R.string.txt_cancel,
                cancelListener = object : BaseDialog.OnDialogCancelListener {
                    override fun onCancelClick(dialog: BaseDialog<*>) {
                        dialog.dismiss()
                        finish()
                    }
                })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewBinding.lavAddNewTracker2Lottie.cancelAnimation()
        SRBleUtil.instance.cancelBleScan()
    }
}