package com.cheng.blzb.manager

import android.text.TextUtils
import com.cheng.blzb.bean.ContactsEntity
import com.example.base.utils.MMKVUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

object ContactsManager {

    fun add(contacts: ContactsEntity) {
        val list = all()
        list.add(0, contacts)
        MMKVUtils.put("contacts_list", Gson().toJson(list))
    }

    fun update(contacts: ContactsEntity) {
        val list = all()
        val oldContacts = list.find { it.id == contacts.id }
        if (oldContacts != null) {
            val index = list.indexOf(oldContacts)
            list.removeAt(index)
            list.add(index, contacts)
        }
        MMKVUtils.put("contacts_list", Gson().toJson(list))
    }

    fun delete(id: String) {
        val list = all()
        val contacts = list.find { it.id == id }
        if (contacts != null) {
            list.remove(contacts)
        }
        MMKVUtils.put("contacts_list", Gson().toJson(list))
    }

    fun all(): MutableList<ContactsEntity> {
        val str = MMKVUtils.getString("contacts_list")
        return if (!TextUtils.isEmpty(str)) {
            Gson().fromJson(str, object : TypeToken<MutableList<ContactsEntity>>(){}.type)
        } else {
            mutableListOf()
        }
    }
}