package top.octopusyan;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.octopusyan.config.OkHttpClientConfig;
import top.octopusyan.controller.LoginController;
import top.octopusyan.http.HttpConfig;
import top.octopusyan.http.config.LogStrategy;
import top.octopusyan.http.request.RequestHandler;
import top.octopusyan.manager.FrpManager;
import top.octopusyan.model.ApplicatonStore;
import top.octopusyan.utils.AlertUtil;
import top.octopusyan.utils.EncryptionUtil;
import top.octopusyan.utils.FxmlUtil;

import java.util.Objects;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description : YanFrp Application
 * @create : 2022-3-29 15:00
 */
public class YanFrpApplication extends Application {
    private static final Logger logger = LoggerFactory.getLogger(YanFrpApplication.class);

    @Override
    public void init() throws Exception {
        super.init();
        logger.info("init...");

        // 初始化加密工具
        EncryptionUtil.init();

        // 初始化应用数据
        ApplicatonStore.init();

        // 初始化frp客户端临时文件
        FrpManager.initFrpc();

        // 网络请求日志
        OkHttpClientConfig.showLog = false;

        // 网络请求设置
        HttpConfig.with(OkHttpClientConfig.httpClient(
                        HttpLoggingInterceptor.Level.HEADERS
                ))
                // 请求服务地址
                .serverPath("https://example.com")
                // 是否打印日志
                .setLogEnabled(true)
                // 设置日志打印策略
                .setLogStrategy(new LogStrategy())
                // 设置请求处理策略
                .setHandler(new RequestHandler())
                // 设置请求重试次数
                .setRetryCount(3)
                // 启用配置
                .into();
    }

    @Override
    public void start(Stage stage) {
        logger.info("start...");

        //  TODO 全局异常处理... (emm有点草率，先这样了。。)
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> Platform.runLater(() -> showErrorDialog(t, e)));
        Thread.currentThread().setUncaughtExceptionHandler(this::showErrorDialog);

        // 初始化弹窗
        AlertUtil.initOwner(stage);

        try {
            // 静态写法无法获取controler
//            StackPane root = FXMLLoader.load(getClass().getResource("/fxml/login.fxml"));

            FXMLLoader fxmlLoader = FxmlUtil.init("/fxml/login.fxml");
            StackPane root = fxmlLoader.load();//底层面板
            stage.initStyle(StageStyle.TRANSPARENT);
            Scene scene = new Scene(root, root.getPrefWidth() + 20, root.getPrefHeight() + 20, Color.TRANSPARENT);
            scene.getStylesheets().addAll(Objects.requireNonNull(getClass().getResource("/css/root.css")).toExternalForm());
            stage.setScene(scene);
            stage.show();

            LoginController controller = fxmlLoader.getController();
            controller.setApplication(this);

        } catch (Throwable t) {
            showErrorDialog(Thread.currentThread(), t);
        }

        logger.debug("start end...");
    }

    private void showErrorDialog(Thread t, Throwable e) {
        e.printStackTrace();
        Platform.runLater(() -> AlertUtil.exceptionAlert(new Exception(e)).show());
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        FrpManager.clearTmp();
        logger.info("stop...");
    }

    public static void main(String[] args) {
        Application.launch(YanFrpApplication.class, args);
    }
}
