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 putBoolean(@MMKVKey key: String, value: Boolean) {
        MMKV.defaultMMKV().encode(key, value)
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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