package com.android.common.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

public class SPUtils {

    private SharedPreferences sharedPreferences;

    private static Map<String, SPUtils> mSpMap = new HashMap<>();

    private SPUtils(String name) {
        sharedPreferences = AppUtils.getAppContext().getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    public static SPUtils getSPUtils()
    {
        return getSPUtils(null);
    }

    public static SPUtils getSPUtils(String name){
        if(TextUtils.isEmpty(name)){
            name = AppUtils.getAppContext().getPackageName();
        }
        if(mSpMap.containsKey(name)){
            return mSpMap.get(name);
        }else {
            SPUtils spUtils = new SPUtils(name);
            mSpMap.put(name, spUtils);
            return spUtils;
        }
    }

    public String getStringValue(String key, String defaultValue){
        return sharedPreferences.getString(key, defaultValue);
    }

    public Float getFloatValue(String key, Float defaultValue){
        return sharedPreferences.getFloat(key, defaultValue);
    }

    public Integer getIntValue(String key, Integer defaultValue){
        return sharedPreferences.getInt(key, defaultValue);
    }

    public Long getLongValue(String key, Long defaultValue){
        return sharedPreferences.getLong(key, defaultValue);
    }

    public Boolean getBooleanValue(String key, Boolean defaultValue){
        return sharedPreferences.getBoolean(key, defaultValue);
    }

    /**
     * 从配置文件里读取值
     *
     * @param key   键，String
     * @param value 值，基本类型
     */
    public void putValue(String key, Object value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        }
        editor.apply();
    }
}
