package com.abbidot.tracker.dialog

import android.content.Context
import android.view.View
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.DFUStateBean
import com.abbidot.tracker.databinding.DialogTrackerDfuListLayoutBinding
import com.abbidot.tracker.util.ViewUtil

/**
 *Created  by .yzq on 2022/1/7/007.
 * @link
 * @description:TrackerDFU升级弹窗
 */
class TrackerDFUStateDialog(context: Context, adapter: BaseRecyclerAdapter<DFUStateBean>) :
    BaseDialog<DialogTrackerDfuListLayoutBinding>(
        DialogTrackerDfuListLayoutBinding::inflate, context
    ) {

    private val mDFUStateList = mutableListOf<DFUStateBean>()

    private val mAdapter = adapter

    override fun initView() {
        setCancelable(false)
        mViewBinding.apply {
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                context, trackDfuStateListRecyclerView, mAdapter, bottom = 0
            )
            btnTrackDfuOk.setChangeAlphaWhenPress(true)
            btnTrackDfuCancel.setChangeAlphaWhenPress(true)
            btnTrackDfuCancel.setOnClickListener {
                dismiss()
            }
        }
    }

    fun setContent(string: String) {
        mViewBinding.apply {
            tvTrackDfuContent.text = string
            btnTrackDfuOk.visibility = View.VISIBLE
            btnTrackDfuCancel.visibility = View.VISIBLE
            svTrackDfuContent.visibility = View.VISIBLE
            trackDfuStateListRecyclerView.visibility = View.GONE
            mDFUStateList.clear()
        }
    }

    fun startSureDFU(onClick: () -> Unit) {
        mViewBinding.btnTrackDfuOk.setOnClickListener {
            mViewBinding.apply {
                btnTrackDfuOk.visibility = View.GONE
                btnTrackDfuCancel.visibility = View.GONE
                svTrackDfuContent.visibility = View.GONE
                trackDfuStateListRecyclerView.visibility = View.VISIBLE
            }
            onClick()
        }
    }

    fun addData(data: DFUStateBean) {
        var isAdd = false
        var potion = 0
        for (i in 0 until mDFUStateList.size) {
            val dfuStateBean = mDFUStateList[i]
            if (dfuStateBean.stateName == data.stateName) {
                dfuStateBean.filePath = data.filePath
                dfuStateBean.progress = data.progress
                isAdd = true
                potion = i
                break
            }
        }
        if (isAdd) {
            mAdapter.notifyItemChanged(potion)
        } else {
            LogUtil.e("未添加过${mDFUStateList.size}")
            mDFUStateList.add(data)
            mAdapter.setData(mDFUStateList)
            mAdapter.notifyDataSetChanged()
            //自动定位滚动最后一个item
            mViewBinding.trackDfuStateListRecyclerView.scrollToPosition(mDFUStateList.size - 1)
        }
    }
}