/*
 * Created by JFormDesigner on Wed Oct 09 08:18:13 EDT 2024
 */

package tech.nevets.tvpn.ui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import net.miginfocom.swing.*;
import tech.nevets.tvpn.Logger;
import tech.nevets.tvpn.auth.AuthManager;
import tech.nevets.tvpn.auth.UserToken;

/**
 * @author steven
 */
public class LoginPanel extends JPanel {
    private static final Logger LOGGER = new Logger(LoginPanel.class);
    private final UIManager uim;

    public LoginPanel(UIManager uim) {
        this.uim =  uim;

        SwingWorker<UserToken, Void> worker = new SwingWorker<>() {
            @Override
            protected UserToken doInBackground() throws Exception {
                statusLabel.setText("Attempting login with stored token...");
                return AuthManager.checkAuth();
            }

            @Override
            protected void done() {
                try {
                    UserToken token = get();

                    // Update the UI on the Event Dispatch Thread
                    if (token.isAuthenticated()) {
                        uim.getUIPanel().updateUserInfo(token.getUsername(), token.getEmail());
                        uim.disposeLoginFrame();
                    } else {
                        statusLabel.setText("Unable to authenticate with stored token, please login");
                    }
                } catch (Exception ex) {
                    LOGGER.error(ex.getMessage());
                    statusLabel.setText("An error occurred during login.");
                }
            }
        };

        initComponents();
        worker.execute();
    }

    private void loginBtn(ActionEvent e) {
        // Immediately update the statusLabel on the UI thread
        this.statusLabel.setText("Logging in...");

        // Use SwingWorker to handle the authentication process in the background
        SwingWorker<UserToken, Void> worker = new SwingWorker<>() {

            @Override
            protected UserToken doInBackground() {
                // This is done in the background thread, so the UI won't be blocked
                return AuthManager.httpAuth(usernameField.getText(), new String(passwordField.getPassword()));
            }

            @Override
            protected void done() {
                try {
                    // Get the result of doInBackground
                    UserToken token = get();

                    // Update the UI on the Event Dispatch Thread
                    if (!token.isAuthenticated()) {
                        statusLabel.setText(token.getMessage());
                        passwordField.setText("");
                        return;
                    }

                    uim.getUIPanel().updateUserInfo(token.getUsername(), token.getEmail());
                    uim.disposeLoginFrame();
                } catch (Exception ex) {
                    LOGGER.error(ex.getMessage());
                    statusLabel.setText("An error occurred during login.");
                }
            }
        };

        // Start the background task
        worker.execute();
    }


    private void enterKeyTyped(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_ENTER) {
            loginBtn(new ActionEvent(e.getSource(), e.getID(), "Login"));
        }
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        usernameLabel = new JLabel();
        usernameField = new JTextField();
        passwordLabel = new JLabel();
        passwordField = new JPasswordField();
        loginBtn = new JButton();
        statusLabel = new JLabel();

        //======== this ========
        setLayout(new MigLayout(
            "hidemode 3",
            // columns
            "[fill]" +
            "[grow,fill]",
            // rows
            "[grow]" +
            "[shrink 0,top]" +
            "[shrink 0]" +
            "[grow,top]" +
            "[]"));

        //---- usernameLabel ----
        usernameLabel.setText("Username");
        add(usernameLabel, "cell 0 1");

        //---- usernameField ----
        usernameField.setMaximumSize(new Dimension(300, 2147483647));
        add(usernameField, "cell 1 1,growx");

        //---- passwordLabel ----
        passwordLabel.setText("Password");
        add(passwordLabel, "cell 0 2");

        //---- passwordField ----
        passwordField.setMaximumSize(new Dimension(300, 2147483647));
        passwordField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                enterKeyTyped(e);
            }
        });
        add(passwordField, "cell 1 2,growx");

        //---- loginBtn ----
        loginBtn.setText("Login");
        loginBtn.setMaximumSize(new Dimension(200, 22));
        loginBtn.setMinimumSize(new Dimension(100, 22));
        loginBtn.addActionListener(e -> loginBtn(e));
        add(loginBtn, "cell 0 3 2 1,alignx center,growx 0");
        add(statusLabel, "cell 0 4 2 1");
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel usernameLabel;
    private JTextField usernameField;
    private JLabel passwordLabel;
    private JPasswordField passwordField;
    private JButton loginBtn;
    private JLabel statusLabel;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
