package com.tofly.latte_core.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Base64;

import com.tofly.latte_core.config.Latte;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.HashSet;

/**
 * @ClassName: LattePreference
 * @Description: 共享参数工具类
 * @Author: Rivan
 * @CreateDate: 2020/9/1 0:15
 * @UpdateDate: 2020/9/1 0:15
 */
public final class LattePreference {

    /**
     * 提示:
     * Activity.getPreferences(int mode)生成 Activity名.xml 用于Activity内部存储
     * PreferenceManager.getDefaultSharedPreferences(Context)生成 包名_preferences.xml
     * Context.getSharedPreferences(String name,int mode)生成name.xml
     */
    private static final SharedPreferences PREFERENCES =
            PreferenceManager.getDefaultSharedPreferences(Latte.getApplicationContext());
    private static final String APP_PREFERENCES_KEY = "profile";

    private static SharedPreferences getAppPreference() {
        return PREFERENCES;
    }

    private static SharedPreferences getPreference(String name) {
        return Latte.getApplicationContext().getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    public static void setAppProfile(String val) {
        getAppPreference()
                .edit()
                .putString(APP_PREFERENCES_KEY, val)
                .apply();
    }

    public static void removeCart(String itemId) {
        HashSet<String> carts = getCart();
        carts.remove(itemId);
        setCart(carts);
    }

    public enum LatteFlag {
        CART
    }

    public static String getAppProfile() {
        return getAppPreference().getString(APP_PREFERENCES_KEY, null);
    }

//    public static JSONObject getAppProfileJson() {
//        final String profile = getAppProfile();
//        return JSON.parseObject(profile);
//    }

    public static void removeAppProfile() {
        getAppPreference()
                .edit()
                .remove(APP_PREFERENCES_KEY)
                .apply();
    }

    public static void clearAppPreferences() {
        getAppPreference()
                .edit()
                .clear()
                .apply();
    }

    public static void setCart(HashSet<String> list) {
        getAppPreference()
                .edit()
                .putStringSet(LatteFlag.CART.name(), list)
                .apply();
    }

    public static HashSet<String> getCart() {
        return (HashSet<String>) getAppPreference().getStringSet(LatteFlag.CART.name(), new HashSet<String>());
    }

    public static void setAppFlag(String key, boolean flag) {
        getAppPreference()
                .edit()
                .putBoolean(key, flag)
                .apply();
    }

    public static void setAppFlag(String key, int flag) {
        getAppPreference()
                .edit()
                .putInt(key, flag)
                .apply();
    }

    public static boolean getAppFlag(String key) {
        return getAppPreference()
                .getBoolean(key, false);
    }

    public static int getAppint(String key) {
        return getAppPreference().getInt(key, 0);
    }

    public static void addCustomAppProfile(String key, String val) {
        getAppPreference()
                .edit()
                .putString(key, val)
                .apply();
    }

    public static String getCustomAppProfile(String key) {
        return getAppPreference().getString(key, "");
    }

    public static void setString(String key, String name) {
        getAppPreference()
                .edit()
                .putString(key, name)
                .apply();
    }

    //    删除单个某个值
    public static void clearStringByKey(String key) {
        getAppPreference()
                .edit()
                .remove(key)
                .apply();
    }

    public static String getString(String key) {
        return getAppPreference().getString(key, null);
    }

    public static void setInt(String key, int tag) {
        getAppPreference()
                .edit()
                .putInt(key, tag)
                .apply();
    }

    public static int getInt(String key) {
        return getAppPreference().getInt(key, 0);
    }

    public static long getLong(String name, String key, int default_value) {
        SharedPreferences preferences = getPreference(name);
        return preferences.getLong(key, default_value);
    }

    public static void setLong(String name, String key, long value) {
        getPreference(name)
                .edit()
                .putLong(key, value)
                .apply();
    }

    public static void setInt(String name, String key, int value) {
        getPreference(name)
                .edit()
                .putInt(key, value)
                .apply();
    }

    public static int getInt(String name, String key, int default_value) {
        SharedPreferences preferences = getPreference(name);
        return preferences.getInt(key, default_value);
    }

    public static void setBoolean(String name, String key, boolean value) {
        getPreference(name)
                .edit()
                .putBoolean(key, value)
                .apply();
    }

    public static boolean getBoolean(String name, String key, boolean default_value) {
        SharedPreferences preferences = getPreference(name);
        return preferences.getBoolean(key, default_value);
    }

    public static void setString(String name, String key, String value) {
        getPreference(name)
                .edit()
                .putString(key, value)
                .apply();
    }

    public static String getString(String name, String key, String default_value) {
        SharedPreferences preferences = getPreference(name);
        return preferences.getString(key, default_value);
    }

    /**
     * 使用SharedPreference保存序列化对象
     * 用Base64.encode将字节文件转换成Base64编码保存在String中
     *
     * @param context 上下文
     * @param key     储存对象的key
     * @param object  object对象  对象必须实现Serializable序列化，否则会出问题，
     *                out.writeObject 无法写入 Parcelable 序列化的对象
     */
    public static void setObject(Context context, String key, Object object) {
        //创建字节输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //创建字节对象输出流
        ObjectOutputStream out = null;
        try {
            //然后通过将字对象进行64转码，写入sp中
            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectValue = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor editor = getAppPreference().edit();
            editor.putString(key, objectValue);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }

                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取SharedPreference保存的对象
     * 使用Base64解密String，返回Object对象
     *
     * @param context 上下文
     * @param key     储存对象的key
     * @param <T>     泛型
     * @return 返回保存的对象
     */
    public static <T> T getObject(Context context, String key) {

        if (getAppPreference().contains(key)) {
            String objectValue = getAppPreference().getString(key, null);
            byte[] buffer = Base64.decode(objectValue, Base64.DEFAULT);
            //一样通过读取字节流，创建字节流输入流，写入对象并作强制转换
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
