package com.abbidot.tracker.deprecated.ui.activity.vm

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.DiffUtil
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDiffCallBack
import com.abbidot.tracker.bean.LabelBean
import com.abbidot.tracker.retrofit2.NetworkApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *Created  by .yzq on 2022/3/3/003.
 * @link
 * @description:
 */
class AddPetLabelsViewModel : ViewModel() {

    val mPetLabelsLiveData = MutableLiveData<Result<MutableList<String>>>()
    val mLabelListLiveData = MutableLiveData<MutableList<LabelBean>>()

    fun getPetLabels(activity: BaseActivity<*>) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.getPetLabels()
            mPetLabelsLiveData.value = result
        }
    }

    /**
     * 多个标签，隔开的字符串转数组
     */
    fun getLabelData(label: String) {
        if (TextUtils.isEmpty(label)) return
        val labels = label.split(",")
        if (labels.isNotEmpty()) {
            val labelList = mutableListOf<LabelBean>()
            labels.forEach { str ->
                val labelBean = LabelBean(str)
                labelList.add(labelBean)
            }
            mLabelListLiveData.value = labelList
        }
    }

    fun setLabelData(adapter: BaseRecyclerAdapter<LabelBean>, newList: MutableList<LabelBean>) {
        val oldList = adapter.getData()
        if (oldList.size == 0) {
            adapter.setData(newList, true)
            return
        }
        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                adapter.setData(newList)
                DiffUtil.calculateDiff(BaseDiffCallBack(oldList, newList), true)
            }.dispatchUpdatesTo(adapter)
        }
    }
}