package com.gensee.multi_instance.ui.viewmodel

import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.gensee.multi_instance.ui.DemoInitParam
import com.gensee.multi_instance.utils.SharedPreferencesHelper
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.burnoutcrew.reorderable.ItemPosition
import java.lang.reflect.Type

/**
 *  author : guohaonan
 *  date : 2024/1/23 13:48
 *  description :
 */
class InitParamsViewModel : ViewModel() {

    var videoInfoList by mutableStateOf(listOf<DemoInitParam>())

    fun addItem(initParam: DemoInitParam) {

        videoInfoList = videoInfoList.toMutableList().apply {
//            removeIf { it is  BtnData}
            add(initParam)
//            add(BtnData())
        }
    }

    fun updateItem(initParam: DemoInitParam) {

    }

    fun deleteItem(initParam: DemoInitParam) {
        videoInfoList = videoInfoList - initParam
    }

    fun save(context:Context){
        saveList(context,videoInfoList.toMutableList())
    }

    fun restore(context:Context) {
        videoInfoList = getList(context).toMutableList()
    }

    fun restoreFromJson(json:String):Boolean{
        val type: Type = object : TypeToken<List<DemoInitParam>>() {}.type
        videoInfoList = gson.fromJson(json, type) ?: emptyList()

        return videoInfoList.isNotEmpty()
    }

    private val gson: Gson = Gson()

    private fun saveList(context: Context, list: List<DemoInitParam>) {
        val jsonString = gson.toJson(list)
        SharedPreferencesHelper.saveJson(context,jsonString)
    }

    private fun getList(context: Context): List<DemoInitParam> {
        val type: Type = object : TypeToken<List<DemoInitParam>>() {}.type
        return gson.fromJson(SharedPreferencesHelper.getJson(context), type) ?: emptyList()
    }


}