package top.octopusyan.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.commons.io.FileUtils;
import top.octopusyan.manager.http.request.ProxySetup;
import top.octopusyan.utils.EncryptionUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description :  应用信息
 * @create : 2022-4-4 17:22
 */
public class ApplicatonStore {
    public static final String APP_NAME = "YanFrp";
    public static final String APP_VERSION = "1.0.4";
    public static final String appDataDirPath = System.getProperty("user.home") + File.separator + "AppData" + File.separator + "Local" + File.separator + "yanfrp";
    public static final String appDataFilePath = appDataDirPath + File.separator + "yanfrp";
    private static final File appDataDir = new File(appDataDirPath);
    private static final File appDataFile = new File(appDataFilePath);
    private static final String ACCOUNT_KEY = "YANFRP_ACCOUNT";
    private static final String PASSWORD_KEY = "YANFRP_PASSWORD";
    private static final String AUTO_LOGIN_KEY = "YANFRP_AUTO_LOGIN";
    private static final String REMEMBER_ME_KEY = "YANFRP_REMEMBER_ME";
    private static final String SELECT_PROXY_NAME_KEY = "YANFRP_SELECT_PROXY_NAME";
    private static final SimpleStringProperty account = new SimpleStringProperty();
    private static final SimpleStringProperty password = new SimpleStringProperty();
    private static final SimpleStringProperty email = new SimpleStringProperty();
    private static final SimpleBooleanProperty autoLogin = new SimpleBooleanProperty();
    private static final SimpleBooleanProperty rememberMe = new SimpleBooleanProperty();
    private static final SimpleBooleanProperty registerSuccess = new SimpleBooleanProperty();
    private static final ObservableList<ProxySetup> proxyList = FXCollections.observableList(new ArrayList<>());
    private static final SimpleIntegerProperty selectProxy = new SimpleIntegerProperty(0);
    private static final SimpleStringProperty userToken = new SimpleStringProperty();
    public static String selectProxyName = null;

    public static void setAccount(String account) {
        ApplicatonStore.account.set(account);
    }

    public static void setEmail(String email) {
        ApplicatonStore.email.set(email);
    }

    public static void setPassword(String password) {
        ApplicatonStore.password.set(password);
    }

    public static String getAccount() {
        return account.get();
    }

    public static SimpleStringProperty accountProperty() {
        return account;
    }

    public static String getEmail() {
        return email.get();
    }

    public static String getPassword() {
        return password.get();
    }

    public static SimpleStringProperty passwordProperty() {
        return password;
    }

    public static void setAutoLogin(boolean autoLogin) {
        ApplicatonStore.autoLogin.set(autoLogin);
    }

    public static void setRememberMe(boolean rememberMe) {
        ApplicatonStore.rememberMe.set(rememberMe);
    }

    public static boolean isAutoLogin() {
        return autoLogin.get();
    }

    public static SimpleBooleanProperty autoLoginProperty() {
        return autoLogin;
    }

    public static boolean isRememberMe() {
        return rememberMe.get();
    }

    public static SimpleBooleanProperty rememberMeProperty() {
        return rememberMe;
    }

    public static void setRegisterSuccess(boolean registerSuccess) {
        ApplicatonStore.registerSuccess.set(registerSuccess);
    }

    public static boolean isRegisterSuccess() {
        return registerSuccess.get();
    }

    public static ObservableList<ProxySetup> proxyList() {
        return proxyList;
    }

    public static void setProxyList(List<ProxySetup> proxySetupList) {
        proxyList.setAll(proxySetupList);
    }

    public static void addProxyList(ProxySetup proxySetup) {
        proxyList.add(proxySetup);
    }

    public static SimpleStringProperty userTokenProperty() {
        return userToken;
    }

    public static String getUserToken() {
        return userToken.get();
    }

    public static void setUserToken(String token) {
        userToken.set(token);
    }

    public static void selectProxy(int selectProxy) {
        ApplicatonStore.selectProxy.set(selectProxy);
    }

    public static int selectProxy() {
        return selectProxy.get();
    }

    /**
     * 初始化应用数据
     */
    public static void init() {
        // 检查应用目录
        checkAppData();
        // 注册状态
        setRegisterSuccess(false);
        // 应用数据
        JSONObject appDataJson = new JSONObject();
        try {
            String str = FileUtils.readFileToString(appDataFile, StandardCharsets.UTF_8);
            appDataJson = JSON.parseObject(EncryptionUtil.decodeAppData(str));
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (appDataJson == null) return;

        // 账号
        if (appDataJson.containsKey(ACCOUNT_KEY)) account.set(appDataJson.getString(ACCOUNT_KEY));
        // 密码
        if (appDataJson.containsKey(PASSWORD_KEY)) password.set(appDataJson.getString(PASSWORD_KEY));
        // 自动登录
        if (appDataJson.containsKey(AUTO_LOGIN_KEY)) autoLogin.set(appDataJson.getBoolean(AUTO_LOGIN_KEY));
        // 记住
        if (appDataJson.containsKey(REMEMBER_ME_KEY)) rememberMe.set(appDataJson.getBoolean(REMEMBER_ME_KEY));
        // 已选择隧道
        if (appDataJson.containsKey(SELECT_PROXY_NAME_KEY))
            selectProxyName = appDataJson.getString(SELECT_PROXY_NAME_KEY);
    }

    /**
     * 序列化应用信息到本地
     */
    public static void save() {
        // 检查应用目录
        checkAppData();
        // 保存数据
        JSONObject appDataJson = new JSONObject();
        // 账号
        if (rememberMe.get() && account.get() != null) appDataJson.put(ACCOUNT_KEY, account.get());
        // 密码
        if (rememberMe.get() && password.get() != null) appDataJson.put(PASSWORD_KEY, password.get());
        // 选择隧道
        if (selectProxy.getValue() != null && proxyList.size() > 0 && proxyList.size() > selectProxy.get())
            appDataJson.put(SELECT_PROXY_NAME_KEY, proxyList.get(selectProxy.getValue()).getProxy_name());
        // 自动登录
        appDataJson.put(AUTO_LOGIN_KEY, autoLogin.get());
        // 记住
        appDataJson.put(REMEMBER_ME_KEY, rememberMe.get());

        try {
            String appDataStr = EncryptionUtil.encodeAppData(appDataJson.toJSONString());
            FileUtils.write(appDataFile, appDataStr, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void rememberMe(String password) {
        // 密码
        if (isRememberMe()) {
            setPassword(password);
        }
    }

    public static void logout() {
        setRegisterSuccess(false);
        setAutoLogin(false);
        setRememberMe(false);
        setPassword("");
    }

    /**
     * 检查应用数据目录
     */
    private static void checkAppData() {

        // 应用目录
        if (!appDataDir.exists()) appDataDir.mkdirs();

        // 应用数据文件
        if (!appDataFile.exists()) {
            try {
                appDataFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
