package top.r3944realms.docchecktoolrefactored.ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Spinner;
import javafx.scene.input.MouseDragEvent;
import javafx.stage.Stage;
import top.r3944realms.docchecktoolrefactored.System;
import top.r3944realms.docchecktoolrefactored.core.Setting;
import top.r3944realms.docchecktoolrefactored.ui.extend.LongSpinnerValueFactory;
import top.r3944realms.docchecktoolrefactored.ui.utils.DialogUtil;

import java.net.URL;
import java.util.ResourceBundle;

public class SettingDialogController implements Initializable {

    @FXML private CheckBox enableStepCB;
    @FXML private Button resetB, saveB, cancelB;
    @FXML private Spinner<Long> scanTimeOutS, taskTimeOutS;

    private Setting setting;

    // Spinner 范围常量
    private static final int SINGLE_MIN = 1;
    private static final int SINGLE_MAX = 3600;
    private static final int TOTAL_MIN = 1;
    private static final int TOTAL_MAX = 86400;
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 获取当前配置
        setting = System.getSetting();

        // 初始化 Spinner
        scanTimeOutS.setValueFactory(new LongSpinnerValueFactory(1, 3600, setting.getScanTimeout()));
        scanTimeOutS.setEditable(true);
        taskTimeOutS.setValueFactory(new LongSpinnerValueFactory(1, 3600 * 24, setting.getTaskTimeout()));
        taskTimeOutS.setEditable(true);

        // 添加焦点离开时校验
        addSpinnerValidation(scanTimeOutS, SINGLE_MIN, SINGLE_MAX);
        addSpinnerValidation(taskTimeOutS, TOTAL_MIN, TOTAL_MAX);
        enableStepCB.setSelected(setting.isEnableStep());
    }

    /** 保存修改 */
    @FXML
    void onSave(ActionEvent actionEvent) {
        // 更新配置对象
        setting.setScanTimeout(scanTimeOutS.getValue());
        setting.setTaskTimeout(taskTimeOutS.getValue());
        setting.setEnableStep(enableStepCB.isSelected());
        // 保存到配置文件
        System.saveSettingsNow();
        // 通知主界面刷新按钮状态
        MainStageController mainController = SceneManager.getMainController();
        if(mainController != null){
            mainController.updateStepButtonsVisibility();
        }
        closeDialog();
    }

    /** 重置为默认值 */
    @FXML
    void onReset(ActionEvent actionEvent) {
        scanTimeOutS.getValueFactory().setValue(30L);       // 默认单次超时
        taskTimeOutS.getValueFactory().setValue(300L);       // 默认总超时
        enableStepCB.setSelected(false);
    }

    /** 取消修改 */
    @FXML
    void onCancel(ActionEvent actionEvent) {
        closeDialog();
    }

    @FXML
    void onCheckOne(MouseDragEvent mouseDragEvent) {
        validateSpinnerValue(scanTimeOutS, 30, 3600);
    }

    @FXML
    void onCheckTwo(MouseDragEvent mouseDragEvent) {
        validateSpinnerValue(taskTimeOutS, 60, 3600 * 24);
    }
    @FXML
    void onSettingThree(ActionEvent actionEvent) {

    }

    /** 给 Spinner 添加离开焦点校验 */
    private void addSpinnerValidation(Spinner<Long> spinner, long min, long max) {
        spinner.getEditor().focusedProperty().addListener((obs, oldVal, newVal) -> {
            if (!newVal) { // 焦点离开时触发
                validateSpinnerValue(spinner, min, max);
            }
        });
    }

    /** 校验 Spinner 的值是否在范围内，如果超出则纠正并提示 */
    private void validateSpinnerValue(Spinner<Long> spinner, long min, long max) {
        try {
            long value = Integer.parseInt(spinner.getEditor().getText());
            if (value < min || value > max) {
                // 超出范围则纠正
                long corrected = Math.max(min, Math.min(value, max));
                spinner.getValueFactory().setValue(corrected);

                // 弹出提示
                DialogUtil.showWarningDialog("输入警告", "输入的值超出范围，已自动调整为 " + corrected);
            }
        } catch (NumberFormatException e) {
            // 非数字输入恢复原来的值
            spinner.getEditor().setText(spinner.getValue().toString());
            DialogUtil.showWarningDialog("输入警告","输入非法，已恢复为原值 " + spinner.getValue());
        }
    }
    /** 关闭对话框 */
    private void closeDialog() {
        Stage stage = (Stage) cancelB.getScene().getWindow();
        stage.close();
    }
}
