/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2021 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.installer.screens;

import org.jboss.installer.common.InstallerDialogs;
import org.jboss.installer.common.UiResources;
import org.jboss.installer.core.InstallationData;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.Screen;
import org.jboss.installer.core.ValidationResult;
import org.jboss.installer.postinstall.task.LDAPManagementAuthConfig;
import org.jboss.installer.validators.LDAPValidator;
import org.jboss.installer.validators.PasswordEqualityValidator;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;

public class LDAPConnectionScreen extends DefaultScreen {

    public static final String NAME = "LDAPConnectionScreen";
    public static final String TITLE_KEY="ldap_connection.title";
    public static final String LDAP_SCREEN_DESCRIPTION = "ldap_screen.description";
    public static final String LDAP_SCREEN_LABEL_CONNECTION_NAME = "ldap_screen.label.connection_name";
    public static final String LDAP_SCREEN_LABEL_DIRECTORY_SERVER = "ldap_screen.label.directory_server";
    public static final String LDAP_SCREEN_LABEL_DISTINGUISHED_NAME = "ldap_screen.label.distinguished_name";
    public static final String LDAP_SCREEN_LABEL_DN_PASSWORD = "ldap_screen.label.dn_password";
    public static final String LDAP_SCREEN_LABEL_DN_PASSWORD_CONFIRM = "ldap_screen.label.dn_password_confirm";
    public static final String LDAP_SCREEN_BUTTON_TEST_CONNECTION = "ldap_screen.button.test_connection";
    private static final String LDAP_SCREEN_CONNECTION_SUCCESS = "ldap_screen.connection.success";
    private final JButton testConnectionButton = createButton(LDAP_SCREEN_BUTTON_TEST_CONNECTION, this::validateLdapConnection);
    private final JPasswordField passwordConfirmField = createPasswordField();
    private final JPasswordField passwordField = createPasswordField();

    private final JTextField dnField = createTextField("uid=admin,ou=system");
    private final JTextField urlField = createTextField("ldap://127.0.0.1:389");
    private final JTextField connectionField = createTextField("ldap.connection");
    private LDAPManagementAuthConfig config;

    public LDAPConnectionScreen(Screen parent, LanguageUtils langUtils, boolean isActive) {
        super(parent, langUtils, isActive);
    }

    @Override
    public String getTitle() {
        return langUtils.getString(TITLE_KEY);
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public JPanel getContent() {
        JPanel content = new JPanel(new GridBagLayout());
        final GridBagConstraints c = initializeConstraints();
        c.gridwidth = 2;

        c.insets = DESCRIPTION_INSET;
        content.add(createDescription(LDAP_SCREEN_DESCRIPTION), c);
        c.gridy++;

        c.gridwidth = 1;

        addField(content, c, LDAP_SCREEN_LABEL_CONNECTION_NAME, connectionField);

        addField(content, c, LDAP_SCREEN_LABEL_DIRECTORY_SERVER, urlField);

        addField(content, c, LDAP_SCREEN_LABEL_DISTINGUISHED_NAME, dnField);

        addField(content, c, LDAP_SCREEN_LABEL_DN_PASSWORD, passwordField);

        addField(content, c, LDAP_SCREEN_LABEL_DN_PASSWORD_CONFIRM, passwordConfirmField);

        c.gridy++;
        c.weightx = LEFT_COLUMN_WEIGHT;
        content.add(testConnectionButton, c);

        c.gridy++;
        fillEmptySpace(content, c);

        return content;
    }

    @Override
    public JComponent getDefaultFocusComponent() {
        return connectionField;
    }

    private void validateLdapConnection(ActionEvent actionEvent) {
        // validate password
        ValidationResult result = new PasswordEqualityValidator(langUtils)
                .validate(passwordField.getText(), passwordConfirmField.getText());
        if (result.getResult() != ValidationResult.Result.OK) {
            InstallerDialogs.showErrorMessage(result.getMessage(), langUtils, null);
            return;
        }

        LDAPManagementAuthConfig config = new LDAPManagementAuthConfig(
                connectionField.getText(), urlField.getText(), dnField.getText() ,passwordField.getText());

        result = new LDAPValidator(langUtils).validateData(config);
        if (result.getResult() != ValidationResult.Result.OK) {
            InstallerDialogs.showErrorMessage(result.getMessage(), langUtils, null);
        } else {
            InstallerDialogs.showInfoMessage(langUtils.getString(LDAP_SCREEN_CONNECTION_SUCCESS), langUtils, null);
        }
    }

    @Override
    public ValidationResult validate() {
        LDAPManagementAuthConfig config = new LDAPManagementAuthConfig(
                UiResources.readTextValue(connectionField), UiResources.readTextValue(urlField),
                UiResources.readTextValue(dnField), UiResources.readTextValue(passwordField));

        if (!validateNonEmpty(config.getUrl()) ||
                !validateNonEmpty(config.getConnection()) ||
                !validateNonEmpty(config.getPassword()) ||
                !validateNonEmpty(config.getDn())) {
            return ValidationResult.error(langUtils.getString("ldap_screen.empty_field.error"));
        }

        if(config.getConnection().matches(".*\\s+.*")) {
            return ValidationResult.error(langUtils.getString("ldap_screen.connection_whitespace.error"));
        }

        final ValidationResult result = new PasswordEqualityValidator(langUtils).validate(passwordField.getText(), passwordConfirmField.getText());

        if (result.getResult() == ValidationResult.Result.OK) {
            this.config = config;
        }

        return result;
    }

    @Override
    public void record(InstallationData installationData) {
        installationData.putConfig(config);
    }

    @Override
    public void rollback(InstallationData installationData) {
        installationData.removeConfig(LDAPManagementAuthConfig.class);
        // reset password confirmation to check that the user remembers previously entered value - https://bugzilla.redhat.com/show_bug.cgi?id=1088152#c3
        this.passwordConfirmField.setText("");
    }

    private boolean validateNonEmpty(String text) {
        return text != null && !text.isEmpty();
    }
}
