package com.rv.component.utils;

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

import java.lang.ref.WeakReference;

/*********
 * 缓存数据，账号级别的
 */
public class Cookie {

    private final static String COOKIE_FILE = "cookie";

    private static SharedPreferences preferences;

    private static WeakReference<Context> weakReference = null;

    public static void init(Context context) {
        weakReference = new WeakReference<>(context);
    }

    private static SharedPreferences getPreference() {
        if (preferences == null) {
            preferences = weakReference.get().getSharedPreferences(COOKIE_FILE, Context.MODE_PRIVATE);
        }
        return preferences;
    }

    public static void save(Context context, String key, String s) {
        getPreference().edit().putString(key, s).commit();
    }

    public static void save(Context context, String key, int i) {
        getPreference().edit().putInt(key, i).commit();
    }

    public static void save(Context context, String key, long l) {
        getPreference().edit().putLong(key, l).commit();
    }

    public static void save(Context context, String key, boolean b) {
        getPreference().edit().putBoolean(key, b).commit();
    }

    public static void save(Context context, String key, float f) {
        getPreference().edit().putFloat(key, f).commit();
    }

    public static String getStringValue(Context context, String key) {
        return getStringValue(context, key, "");
    }

    public static String getStringValue(Context context, String key, String def) {
        return getPreference().getString(key, def);
    }

    public static int getIntValue(Context context, String key) {
        return getIntValue(context, key, -1);
    }

    public static int getIntValue(Context context, String key, int def) {
        return getPreference().getInt(key, def);
    }

    public static long getLongValue(Context context, String key) {
        return getLongValue(context, key, 0l);
    }

    public static long getLongValue(Context context, String key, long def) {
        return getPreference().getLong(key, def);
    }

    public static float getFloatValue(Context context, String key) {
        return getFloatValue(context, key, 0f);
    }

    public static float getFloatValue(Context context, String key, float def) {
        return getPreference().getFloat(key, def);
    }

    public static boolean getBooleanValue(Context context, String key) {
        return getBooleanValue(context, key, false);
    }

    public static boolean getBooleanValue(Context context, String key, boolean def) {
        return getPreference().getBoolean(key, def);
    }

    public static void clear(Context context) {
        getPreference().edit().clear().commit();
    }
}
