package top.r3944realms.docchecktoolrefactored.ui;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import lombok.extern.slf4j.Slf4j;
import top.r3944realms.docchecktoolrefactored.System;
import top.r3944realms.docchecktoolrefactored.ui.utils.DialogUtil;
import top.r3944realms.docchecktoolrefactored.util.LoggerMarker;

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

/**
 * 登录场景控制器
 */
@Slf4j
public class LoginStageController implements Initializable {
    /**
     * The Login button.
     */
    @FXML private Button loginButton;
    /**
     * The Main pane.
     */
    @FXML private BorderPane mainPane;
    @FXML private Label versionL;
    @FXML private TextField usernameField;
    @FXML private PasswordField passwordField;

    @FXML
    private void handleLogin() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        if ("admin".equals(username) && "admin".equals(password)) {
            log.info(LoggerMarker.DEBUG_MARKER, "{} Login successful", username);
            SceneManager.switchMainView();
        } else {
            log.info(LoggerMarker.DEBUG_MARKER, "Invalid username or password");
            DialogUtil.showErrorDialog("错误", "输入错误", "用户名或密码错误！");
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //添加 Ctrl + Enter 快捷键
        KeyCodeCombination enter_key_down = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.CONTROL_DOWN);
        // 监听场景属性变化
        SceneManager.tryGetSceneHandler(passwordField, window ->
                        window.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
                            if (enter_key_down.match(event)) {
                                handleLogin();
                            }
                        })
        );
        versionL.setText(System.version());
    }
}