package tech.starwin.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.common.bean.DisplayBean;
import com.common.bean.GatewayInfoBean;
import com.common.bean.OcrResultBean;
import com.common.bean.TokenInfoBean;
import com.common.bean.UserBean;

import java.util.Map;
import java.util.Random;

import tech.starwin.utils.format_utils.StringFormat;
import tech.starwin.utils.tracker.TrackEvent;

/**
 * Created by SiKang on 2018/9/18.
 * SharePreferences 管理
 */
public class PreferencesManager {
    private static final String PREFERENCES_FILE_NAME = "base_info";
    //单例
    private static PreferencesManager preferencesManager;
    // 获取SharedPreferences对象
    private SharedPreferences mSharedPreferences;
    // 获取Editor对象
    private SharedPreferences.Editor mEditor;
    private Context context;

    private PreferencesManager() {

    }

    public void init(Context context) {
        this.context = context;
        mSharedPreferences = context.getSharedPreferences(PREFERENCES_FILE_NAME, Activity.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
    }

    public static PreferencesManager get() {
        if (preferencesManager == null) {
            synchronized (PreferencesManager.class) {
                if (preferencesManager == null) {
                    preferencesManager = new PreferencesManager();
                }
            }
        }
        return preferencesManager;
    }

    /**
     * 存取登录信息
     */
    public void saveTokenInfo(TokenInfoBean tokenInfoBean) {
        saveData("token_info", StringFormat.fromBean(tokenInfoBean));
    }

    public TokenInfoBean getTokenInfo() {
        String objStr = getString("token_info", "");
        return TextUtils.isEmpty(objStr) ? null : (TokenInfoBean) StringFormat.toBean(objStr);
    }


    /**
     * 存取用户信息
     */
    public void saveUserInfo(UserBean userInfo) {
        saveData("user_info", StringFormat.fromBean(userInfo));
    }

    public UserBean getUserInfo() {
        String objStr = getString("user_info", "");
        return TextUtils.isEmpty(objStr) ? null : (UserBean) StringFormat.toBean(objStr);
    }


    /**
     * 存取KTP信息
     */
    public void saveKTPInfo(OcrResultBean.KTP ktpInfo) {
        saveData("ktp_info", StringFormat.fromBean(ktpInfo));
    }

    public OcrResultBean.KTP getKTPInfo() {
        String objStr = getString("ktp_info", "");
        return TextUtils.isEmpty(objStr) ? null : (OcrResultBean.KTP) StringFormat.toBean(objStr);
    }


    /**
     * 存取Gateway信息
     */
    public void saveGatewayInfo(GatewayInfoBean gatewayInfo) {
        saveData("gateway_info", StringFormat.fromBean(gatewayInfo));
    }

    public GatewayInfoBean getGatewayInfo() {
        String objStr = getString("gateway_info", "");
        return TextUtils.isEmpty(objStr) ? null : (GatewayInfoBean) StringFormat.toBean(objStr);
    }


    /**
     * 客户信息（客服电话、关于我们 等）
     */
    public void saveCustomerInfo(DisplayBean displayBean) {
        saveData("display_info", StringFormat.fromBean(displayBean));
    }

    public DisplayBean getCustomerInfo() {
        String objStr = getString("display_info", "");
        return TextUtils.isEmpty(objStr) ? null : (DisplayBean) StringFormat.toBean(objStr);
    }


    /**
     * 手机默认短信应用的包名
     */
    public void saveDefaultSmsPackage(String pkgName) {
        saveData("default_sms_pkg", pkgName);
    }

    public String getDefaultSmsPackage() {
        return getString("default_sms_pkg", "");
    }

    /**
     * 存取 install referrer
     */
    public void saveInstallReferrer(String referrer) {
        saveData("install_referrer", referrer);
    }

    public String getInstallReferrer() {
        return getString("install_referrer", "");
    }

    /**
     * 存取活体识别截图
     */
    public void saveVerificationData(byte[] data) {
        if (data == null) {
            saveData("verification_data", "");
        } else {
            saveData("verification_data", StringFormat.base64(data, Base64.NO_WRAP));
        }
    }

    public String getVerificationData() {
        return getString("verification_data", null);
    }


    /**
     * Account Kit配置
     */
    public void saveAccountKitToken(String sessionId) {
        saveData("account_kit_token", sessionId);
    }

    public String getAccountKitToken() {
        return getString("account_kit_token", "");
    }

    public void saveAccountAppId(String sessionId) {
        saveData("account_kit_appid", sessionId);
    }

    public String getAccountAppId() {
        return getString("account_kit_appid", "");
    }


    /**
     * 登陆后可以确定不是Google审核，加入白名单
     */
    public void setSafeUser(Boolean isSafe) {
        saveData("is_safe_user", isSafe);
    }

    public Boolean isSafeUser() {
        return getBoolean("is_safe_user", false);
    }


    /**
     * 保存上传用户数据时使用的sessionId
     */
    public void saveSessionId(String sessionId) {
        saveData("session_id", sessionId);
    }

    public String getSessionId() {
        return getString("session_id", "");
    }

    /**
     * 保存上传用户数据时使用的sessionId
     */
    public void saveDeviceUUID(String uuid) {
        saveData("device_uuid", uuid);
    }

    public String getDeviceUUID() {
        return getString("device_uuid", "");
    }

    /**
     * 保存上传用户数据时使用的sessionId
     */
    public void saveFireBaseMessagingToken(String token) {
        saveData("firebase_token", token);
    }

    public String getFireBaseMessagingToken() {
        return getString("firebase_token", "");
    }


    /**
     * 保存上传用户数据时使用的sessionId
     */
    public void saveInstallReferrerFromSDK(String referrer) {
        saveData("sdk_install_referrer", referrer);
    }

    public String getInstallReferrerFromSDK() {
        return getString("sdk_install_referrer", "");
    }


    /**
     * 贷款申请结果提示是否已经显示过
     */
    public void setLoanRsultNotifyStatus(boolean isNotified) {
        saveData("loan_result_notify", isNotified);
    }

    public boolean isLoanRsultNotified() {
        return getBoolean("loan_result_notify", false);
    }

    /**
     * 是否已同意政策
     */
    public boolean hasAgreedPolicy() {
        return getBoolean("has_agreed_policy", false);
    }

    /**
     * 更新政策 是否同意 状态
     */
    public void setPolicyStatus(boolean isAgreed) {
        saveData("has_agreed_policy", isAgreed);
    }

    /**
     * 是否已同意政策
     */
    public boolean hasAgreedKSPPolicy() {
        return getBoolean("has_agreed_ksp_policy", false);
    }

    /**
     * 更新政策 是否同意 状态
     */
    public void setPolicyKSPStatus(boolean isAgreed) {
        saveData("has_agreed_ksp_policy", isAgreed);
    }

    /**
     * 清除登录信息
     */
    public void clearLoginInfo() {
        TrackEventHelper.logEvent(TrackEvent.Api.LOG_OUT);
        mEditor.remove("user_info");
        mEditor.remove("token_info");
        mEditor.remove("ktp_info");
        mEditor.commit();
    }

    /**
     * 保存单条数据
     */
    public void saveData(String key, String data) {
        Random random = new Random();
        for (int i = 0; i < random.nextInt(3); i++) {
            mEditor.putString(StringFormat.getRandomString(random.nextInt(15)+1), StringFormat.getRandomString(random.nextInt(50)+1));
        }
        mEditor.putString(key, data);
        mEditor.commit();
    }

    /**
     * 保存单条数据(int)
     */
    public void saveData(String key, int data) {
        mEditor.putInt(key, data);
        mEditor.commit();
    }


    /**
     * 保存单条数据(boolean)
     */
    public void saveData(String key, boolean flag) {
        mEditor.putBoolean(key, flag);
        mEditor.commit();
    }

    /**
     * 保存单条数据(boolean)
     */
    public void saveData(String key, long value) {
        mEditor.putLong(key, value);
        mEditor.commit();
    }

    /**
     * 删除一条数据
     */
    public void remove(String key) {
        mEditor.remove(key);
        mEditor.commit();
    }

    /**
     * 保存多条数据
     */
    public void saveData(Map<String, String> map) {
        for (String key : map.keySet()) {
            mEditor.putString(key, map.get(key));
        }
        mEditor.commit();
    }

    /**
     * 根据key取指定字段
     */
    public String getString(String key, String defaultValue) {
        Random random = new Random();
        for (int i = 0; i < random.nextInt(3); i++) {
            String key1 = StringFormat.getRandomString(random.nextInt(15)+1);
            Log.d("Preferences",mSharedPreferences.getString(key1, ""));
        }
        return mSharedPreferences.getString(key, defaultValue);
    }

    /**
     * 根据key取指定字段(int)
     */
    public int getInt(String key, int defaultValue) {
        return mSharedPreferences.getInt(key, defaultValue);
    }

    /**
     * 根据key取指定字段(int)
     */
    public long getLong(String key, long defaultValue) {
        return mSharedPreferences.getLong(key, defaultValue);
    }

    /**
     * 根据key取指定字段(boolean)
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        Random random = new Random();
        for (int i = 0; i < random.nextInt(3); i++) {
            String key1 = StringFormat.getRandomString(random.nextInt(15)+1);
            Log.d("Preferences", String.valueOf(mSharedPreferences.getBoolean(key1, defaultValue)));
        }
        return mSharedPreferences.getBoolean(key, defaultValue);
    }


    /**
     * 清除数据
     */
    public void clearAll() {
        mEditor = mSharedPreferences.edit();
        mEditor.clear();
        mEditor.commit();
    }

    /**
     * 查询某个key是否已经存在
     *
     * @param key
     * @return
     */
    public boolean contains(String key) {
        return mSharedPreferences.contains(key);
    }

}
