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

    public static final String OFFLINE_TIME = "offline_time";

    public static final String KEY_AGREE_PRIVACY = "key_agree_privacy" ; // 同意隐私权限

    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(String key, String s) {
        getPreference().edit().putString(key, s).commit();
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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