package com.rv.component.utils;

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

import java.lang.ref.WeakReference;

/*******
 * 应用级别的cookie，不会随账号的切换而更改
 */
public class AppCookie {

    private final static String COOKIE_FILE = "app_cookie";

    public final static String KEY_PRERENT_DAYS = "key_prerent_days"  ; // 提前租车天数的key

    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) {
            synchronized (AppCookie.class) {
                if (null == preferences) {
                    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);
    }
}
