package com.guadou.lib_baselib.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * SharedPreferences的工具类，单例模式，可以链式调用
 */

public class SPUtils {
    private static final String SHARED_PREFERENCES_NAME = "config";

    private static SPUtils sharedUtil;
    private Context context;
    private SharedPreferences sharedPreferences;

    private SPUtils(Context context) {
        this.context = context.getApplicationContext();
        this.sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    public static SPUtils getInstance(Context context) {
        synchronized (SPUtils.class) {
            if (sharedUtil == null || sharedUtil.context == null) {
                sharedUtil = new SPUtils(context.getApplicationContext());
            }
        }
        return sharedUtil;
    }

    public SharedPreferences getSharedPreferences() {
        return this.sharedPreferences;
    }

    public SPUtils putString(String key, String value) {
        SharedPreferences preference = this.getSharedPreferences();
        SharedPreferences.Editor editor = preference.edit();
        editor.putString(key, value);
        editor.commit();
        return this;
    }

    public SPUtils putInt(String key, int value) {
        SharedPreferences preference = this.getSharedPreferences();
        SharedPreferences.Editor editor = preference.edit();
        editor.putInt(key, value);
        editor.commit();
        return this;
    }

    public SPUtils putBoolean(String key, boolean value) {
        SharedPreferences preference = this.getSharedPreferences();
        SharedPreferences.Editor editor = preference.edit();
        editor.putBoolean(key, value);
        editor.commit();
        return this;
    }

    public String getString(String key, String defValue) {
        SharedPreferences preference = this.getSharedPreferences();
        return preference.getString(key, defValue);
    }

    public int getInt(String key, int defValue) {
        SharedPreferences preference = this.getSharedPreferences();
        return preference.getInt(key, defValue);
    }

    public boolean getBoolean(String key, boolean defValue) {
        SharedPreferences preference = this.getSharedPreferences();
        return preference.getBoolean(key, defValue);
    }

    public boolean contains(String key) {
        SharedPreferences preference = this.getSharedPreferences();
        return preference.contains(key);
    }

    public SPUtils remove(String key) {
        SharedPreferences preference = this.getSharedPreferences();
        SharedPreferences.Editor editor = preference.edit();
        editor.remove(key);
        editor.commit();
        return this;
    }

    public void clear() {
        SharedPreferences.Editor editor = this.getSharedPreferences().edit();
        editor.clear();
        editor.commit();
    }
}
