package com.qimai.android.tools

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import java.util.concurrent.ConcurrentHashMap

/**
 *   created by wangwei   ON 2019-08-27  email:wangwei_5521@163.com
 *   @version 1.1.1
 *   @Description
 **/
class SharedPreferencesTools {

    private var sp: SharedPreferences? = null
    // applicationContext
    private lateinit var context: Context

    private val defaultKey = "sp_tools_default_key"

    companion object {
        val instance: SharedPreferencesTools by lazy {
            SharedPreferencesTools()
        }
    }

    private val spCache = ConcurrentHashMap<String, SharedPreferences>()


    fun initSp(context: Context) {
        this.context = context
        sp = context.getSharedPreferences(defaultKey, Context.MODE_PRIVATE)
    }


    fun getSpByKey(key: String): SharedPreferences {
        if (spCache[key] == null) {
            spCache[key] = context.getSharedPreferences(key, Context.MODE_PRIVATE)
        }
        return spCache[key]!!
    }

    fun putString(key: String, value: String) {
        check()
        sp?.edit {
            putString(key, value)
        }
    }

    fun putInt(key: String, value: Int) {
        check()
        sp?.edit {
            putInt(key, value).apply()
        }
    }

    fun putBoolean(key: String, value: Boolean) {
        check()
        sp?.edit {
            putBoolean(key, value)
        }
    }

    fun getString(key: String, default: String): String? {
        return sp?.getString(key, default)
    }

    fun getBoolean(key: String, default: Boolean): Boolean? {
        return sp?.getBoolean(key, default)
    }

    fun getInt(key: String, default: Int): Int? {
        return sp?.getInt(key, default)
    }

    fun remove(key: String) {
        check()
        sp?.edit {
            remove(key)
        }
    }

    fun clear() {
        check()
        sp?.edit {
            clear()
        }
    }

    private fun check() {
        checkNotNull(sp) { "mull be invoke initSp" }
    }


}