package com.abbidot.baselibrary.util

import android.app.Application
import android.os.Parcelable
import com.abbidot.baselibrary.constant.MMKVKey
import com.tencent.mmkv.MMKV

/**
 *Created  by .yzq on 2021/11/6/006.
 * @link
 * @description:本类为MMKV的封装类，防止代码入侵
 */
object MMKVUtil {
    fun init(application: Application) {
        MMKV.initialize(application)
    }

    fun getMMKV(): MMKV {
        return MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, Utils.SECRET_KEY, true)
    }

    fun putBoolean(@MMKVKey key: String, value: Boolean) {
        getMMKV().encode(key, value)
    }

    fun getBoolean(@MMKVKey key: String, defaultValue: Boolean = false): Boolean {
        return getMMKV().decodeBool(key, defaultValue)
    }

    fun putString(@MMKVKey key: String, value: String) {
        getMMKV().encode(key, value)
    }

    fun getString(@MMKVKey key: String, defaultValue: String = ""): String {
        return getMMKV().decodeString(key, defaultValue)!!
    }

    fun putInt(@MMKVKey key: String, value: Int) {
        getMMKV().encode(key, value)
    }

    fun getInt(@MMKVKey key: String, defaultValue: Int = 0): Int {
        return getMMKV().decodeInt(key, defaultValue)
    }

    fun putFloat(@MMKVKey key: String, value: Float) {
        getMMKV().encode(key, value)
    }

    fun getFloat(@MMKVKey key: String, defaultValue: Float = 0F): Float {
        return getMMKV().decodeFloat(key, defaultValue)
    }

    fun putLong(@MMKVKey key: String, value: Long) {
        getMMKV().encode(key, value)
    }

    fun getLong(@MMKVKey key: String, defaultValue: Long = 0L): Long {
        return getMMKV().decodeLong(key, defaultValue)
    }

    fun putDouble(@MMKVKey key: String, value: Double) {
        getMMKV().encode(key, value)
    }

    fun getDouble(@MMKVKey key: String, defaultValue: Double = 0.0): Double {
        return getMMKV().decodeDouble(key, defaultValue)
    }

    fun putByteArray(@MMKVKey key: String, value: ByteArray) {
        getMMKV().encode(key, value)
    }

    fun getByteArray(@MMKVKey key: String, defaultValue: ByteArray = ByteArray(0)): ByteArray {
        return getMMKV().decodeBytes(key, defaultValue)!!
    }

    fun putStringSet(@MMKVKey key: String, value: Set<String>) {
        getMMKV().encode(key, value)
    }

    fun getStringSet(
        @MMKVKey key: String,
        defaultValue: Set<String> = mutableSetOf()
    ): Set<String> {
        return getMMKV().decodeStringSet(key, defaultValue)!!
    }

    fun putParcelable(@MMKVKey key: String, value: Parcelable) {
        getMMKV().encode(key, value)
    }

    //清空所有sp
    fun clearAll() {
        //正式测试标识不清空
        val debugIp = getBoolean(MMKVKey.DebugIp, true)
        getMMKV().clearAll()
        putBoolean(MMKVKey.DebugIp, debugIp)
    }

    inline fun <reified T : Parcelable> getParcelable(@MMKVKey key: String): T? {
        return getMMKV().decodeParcelable(key, T::class.java)
    }
}