package com.base.scanqr.ui.main

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.base.scanqr.bean.EmailUIBean
import com.base.scanqr.bean.FunctionUIBean
import com.base.scanqr.bean.ScanBean
import com.base.scanqr.bean.TextUIBean
import com.base.scanqr.bean.WebsiteUIBean
import com.base.scanqr.bean.WifiUIBean
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.SpJsonUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

class HistoryViewModel() : ViewModel() {
    private val TAG = "HistoryViewModel"

    var historyList = arrayListOf<ScanBean>()

    var dataRefreshFinish = AtomicBoolean(false)
    var dataRefreshBack: (() -> Unit)? = null

    fun initData() = viewModelScope.launch(Dispatchers.IO) {
        historyList.clear()

        val wifiList = SpJsonUtils.getSpJsonList<WifiUIBean>(FunctionUIBean.KEY_WIFI)
        wifiList.forEach { it.listContent = it.ssid }
        val textList = SpJsonUtils.getSpJsonList<TextUIBean>(FunctionUIBean.KEY_TEXT)
        textList.forEach { it.listContent = it.content }
        val emailList = SpJsonUtils.getSpJsonList<EmailUIBean>(FunctionUIBean.KEY_EMAIL)
        emailList.forEach { it.listContent = it.address }
        val websiteList = SpJsonUtils.getSpJsonList<WebsiteUIBean>(FunctionUIBean.KEY_WEBSITE)
        websiteList.forEach { it.listContent = it.http }

        historyList.addAll(wifiList)
        historyList.addAll(textList)
        historyList.addAll(emailList)
        historyList.addAll(websiteList)
        historyList.forEach {
            LogEx.logDebug(TAG, "${it.scanType} ${it.createTime} ${it.createType} ${it.listContent}")
        }
        dataRefreshBack?.invoke()
        dataRefreshFinish.set(true)
    }

    fun removeList(tab: Int) {
        val removeList = historyList.filter { it.createType == tab }
        removeList.forEach { removeBean(it) }
    }

    fun removeBean(bean: ScanBean) {
        val scanBean = when (bean.scanType) {
            FunctionUIBean.KEY_WIFI -> bean as WifiUIBean
            FunctionUIBean.KEY_TEXT -> bean as TextUIBean
            FunctionUIBean.KEY_EMAIL -> bean as EmailUIBean
            else -> bean
        }

        SpJsonUtils.removeJsonBean(bean.scanType, scanBean, removeIf = { it1, it2 ->
            it1.createTime == it2.createTime
        })

        historyList.removeIf { it.createTime == bean.createTime }
    }


}