package mage.client.dialog;

import mage.client.MageFrame;
import mage.client.SessionHandler;
import mage.client.preference.MagePreferences;
import mage.remote.Connection;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.util.Arrays;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ResetPasswordDialog extends MageDialog {

    private static final Logger logger = Logger.getLogger(ResetPasswordDialog.class);
    private final ConnectDialog connectDialog;
    private Connection connection;
    private GetAuthTokenTask getAuthTokenTask;
    private ResetPasswordTask resetPasswordTask;

    /**
     * Creates new form ResetPasswordDialog
     */
    public ResetPasswordDialog(ConnectDialog connectDialog) {
        initComponents();
        this.connectDialog = connectDialog;
    }

    public void showDialog() {
        String serverAddress = this.connectDialog.getServer();
        this.txtServer.setText(serverAddress);
        this.txtPort.setText(this.connectDialog.getPort());
        this.txtEmail.setText(MagePreferences.getEmail(serverAddress));
        this.lblStatus.setText("");

        this.setModal(true);
        this.setLocation(50, 50);
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        lblAuthToken = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        lblPasswordConfirmation = new javax.swing.JLabel();
        txtAuthToken = new javax.swing.JTextField();
        btnSubmitNewPassword = new javax.swing.JButton();
        lblPasswordConfirmationReasoning = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        txtPasswordConfirmation = new javax.swing.JPasswordField();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        lblEmail = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        btnGetAuthToken = new javax.swing.JButton();
        lblStatus = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        lblServer = new javax.swing.JLabel();
        txtServer = new javax.swing.JTextField();
        txtPort = new javax.swing.JTextField();
        lblPort = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Reset password");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel6.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel6.setText("Step 2:");

        lblAuthToken.setLabelFor(txtAuthToken);
        lblAuthToken.setText("Auth token:");

        lblPassword.setLabelFor(txtPassword);
        lblPassword.setText("New password:");

        lblPasswordConfirmation.setLabelFor(txtPasswordConfirmation);
        lblPasswordConfirmation.setText("New password:");

        btnSubmitNewPassword.setText("Submit a new password");
        btnSubmitNewPassword.addActionListener(evt -> btnSubmitNewPasswordActionPerformed(evt));

        lblPasswordConfirmationReasoning.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
        lblPasswordConfirmationReasoning.setLabelFor(txtPasswordConfirmation);
        lblPasswordConfirmationReasoning.setText("(confirmation)");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(jPanel2Layout.createSequentialGroup()
                                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                        .addComponent(lblAuthToken, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(lblPassword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                        .addComponent(lblPasswordConfirmation, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(txtAuthToken)
                                                        .addComponent(txtPassword)
                                                        .addComponent(txtPasswordConfirmation)))
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                                .addGap(0, 204, Short.MAX_VALUE)
                                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(lblPasswordConfirmationReasoning, javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addComponent(btnSubmitNewPassword, javax.swing.GroupLayout.Alignment.TRAILING))))
                                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(24, 24, 24)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lblAuthToken)
                                        .addComponent(txtAuthToken, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lblPassword)
                                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lblPasswordConfirmation)
                                        .addComponent(txtPasswordConfirmation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblPasswordConfirmationReasoning)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnSubmitNewPassword)
                                .addContainerGap(9, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel5.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel5.setText("Step 1:");

        lblEmail.setLabelFor(txtEmail);
        lblEmail.setText("Email:");

        btnGetAuthToken.setText("Email an auth token");
        btnGetAuthToken.addActionListener(evt -> btnGetAuthTokenActionPerformed(evt));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(lblEmail)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtEmail))
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addGap(0, 0, Short.MAX_VALUE)
                                                .addComponent(btnGetAuthToken)))
                                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(24, 24, 24)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lblEmail)
                                        .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnGetAuthToken)
                                .addContainerGap())
        );

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(evt -> btnCancelActionPerformed(evt));

        lblServer.setLabelFor(txtServer);
        lblServer.setText("Server:");

        lblPort.setLabelFor(txtPort);
        lblPort.setText("Port:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btnCancel))
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addComponent(lblServer)
                                                        .addComponent(lblPort))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(txtServer)
                                                        .addComponent(txtPort))))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lblServer)
                                        .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblPort))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancel)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGetAuthTokenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGetAuthTokenActionPerformed
        if (this.txtEmail.getText().isEmpty()) {
            MageFrame.getInstance().showError("Please enter an email address.");
            return;
        }

        connection = new Connection();
        connection.setHost(this.txtServer.getText().trim());
        connection.setPort(Integer.valueOf(this.txtPort.getText().trim()));
        PreferencesDialog.setProxyInformation(connection);
        connection.setEmail(this.txtEmail.getText().trim());

        getAuthTokenTask = new GetAuthTokenTask();
        getAuthTokenTask.execute();
    }//GEN-LAST:event_btnGetAuthTokenActionPerformed

    private void btnSubmitNewPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitNewPasswordActionPerformed
        if (this.txtEmail.getText().isEmpty()) {
            MageFrame.getInstance().showError("Please enter an email address.");
            return;
        }
        if (this.txtAuthToken.getText().isEmpty()) {
            MageFrame.getInstance().showError("Please enter an auth token.");
            return;
        }
        if (String.valueOf(this.txtPassword.getPassword()).trim().isEmpty()) {
            MageFrame.getInstance().showError("Please enter a new password.");
            return;
        }
        if (!Arrays.equals(this.txtPassword.getPassword(), this.txtPasswordConfirmation.getPassword())) {
            MageFrame.getInstance().showError("Passwords don't match.");
            return;
        }

        connection = new Connection();
        connection.setHost(this.txtServer.getText().trim());
        connection.setPort(Integer.valueOf(this.txtPort.getText().trim()));
        PreferencesDialog.setProxyInformation(connection);
        connection.setEmail(this.txtEmail.getText().trim());
        connection.setAuthToken(this.txtAuthToken.getText().trim());
        connection.setPassword(String.valueOf(this.txtPassword.getPassword()).trim());

        resetPasswordTask = new ResetPasswordTask();
        resetPasswordTask.execute();
    }//GEN-LAST:event_btnSubmitNewPasswordActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.hideDialog();
    }//GEN-LAST:event_btnCancelActionPerformed

    void disableButtons() {
        btnGetAuthToken.setEnabled(false);
        btnSubmitNewPassword.setEnabled(false);
    }

    void enableButtons() {
        btnGetAuthToken.setEnabled(true);
        btnSubmitNewPassword.setEnabled(true);
    }

    private class GetAuthTokenTask extends SwingWorker<Boolean, Void> {

        private boolean result = false;

        private static final int CONNECTION_TIMEOUT_MS = 2100;

        @Override
        protected Boolean doInBackground() throws Exception {
            lblStatus.setText("Connecting...");
            disableButtons();
            result = SessionHandler.emailAuthToken(connection);
            return result;
        }

        @Override
        protected void done() {
            try {
                get(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
                if (result) {
                    // Save settings.
                    MagePreferences.setEmail(connection.getHost(), connection.getEmail());

                    String message = "Auth token is emailed. Please check your inbox.";
                    lblStatus.setText(message);
                    MageFrame.getInstance().showMessage(message);
                } else {
                    lblStatus.setText("There was an issue while requesting an auth token.");
                }
            } catch (InterruptedException | ExecutionException ex) {
                logger.fatal("Get Auth Token Task error", ex);
            } catch (CancellationException ex) {
                logger.info("Canceled");
                lblStatus.setText("Canceled");
            } catch (TimeoutException ex) {
                logger.fatal("Timeout: ", ex);
            } finally {
                MageFrame.stopConnecting();
                enableButtons();
            }
        }
    }

    private class ResetPasswordTask extends SwingWorker<Boolean, Void> {

        private boolean result = false;

        private static final int CONNECTION_TIMEOUT_MS = 2100;

        @Override
        protected Boolean doInBackground() throws Exception {
            lblStatus.setText("Connecting...");
            disableButtons();
            result = SessionHandler.resetPassword(connection);
            return result;
        }

        @Override
        protected void done() {
            try {
                get(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
                if (result) {
                    // Save settings.
                    MagePreferences.setPassword(connection.getHost(), connection.getPassword());

                    String message = "Password is reset successfully.";
                    lblStatus.setText(message);
                    MageFrame.getInstance().showMessage(message);
                    hideDialog();
                } else {
                    lblStatus.setText("There was an issue while resetting password.");
                }
            } catch (InterruptedException | ExecutionException ex) {
                logger.fatal("Reset Password Task error", ex);
            } catch (CancellationException ex) {
                logger.info("Canceled");
                lblStatus.setText("Canceled");
            } catch (TimeoutException ex) {
                logger.fatal("Timeout: ", ex);
            } finally {
                MageFrame.stopConnecting();
                enableButtons();
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnGetAuthToken;
    private javax.swing.JButton btnSubmitNewPassword;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblAuthToken;
    private javax.swing.JLabel lblEmail;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblPasswordConfirmation;
    private javax.swing.JLabel lblPasswordConfirmationReasoning;
    private javax.swing.JLabel lblPort;
    private javax.swing.JLabel lblServer;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JTextField txtAuthToken;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JPasswordField txtPasswordConfirmation;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtServer;
    // End of variables declaration//GEN-END:variables
}
