/*
 * 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.PostInstallTask;
import org.jboss.installer.postinstall.task.LDAPManagementAuthConfig;
import org.jboss.installer.validators.SearchDnValidator;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;

public class LDAPSecurityRealmScreen extends DefaultScreen{

    public static final String NAME = "LDAPSecurityRealmScreen";
    public static final String TITLE_KEY="ldap_security.title";
    public static final String LDAP_REALM_SCREEN_DESCRIPTION = "ldap_realm_screen.description";
    public static final String LDAP_REALM_SCREEN_REALM_NAME_LABEL = "ldap_realm_screen.realm_name.label";
    public static final String LDAP_REALM_SCREEN_BASE_DN_LABEL = "ldap_realm_screen.base_dn.label";
    public static final String LDAP_REALM_SCREEN_FILTER_TYPE_LABEL = "ldap_realm_screen.filter_type.label";
    public static final String LDAP_REALM_SCREEN_USERNAME_FILTER_LABEL = "ldap_realm_screen.username_filter.label";
    public static final String LDAP_REALM_SCREEN_RECURSIVE_SEARCH_LABEL = "ldap_realm_screen.recursive_search.label";
    public static final String LDAP_REALM_SCREEN_TEST_SEARCH_BUTTON = "ldap_realm_screen.test_search.button";
    public static final String LDAP_REALM_SCREEN_EMPTY_FIELD_ERROR = "ldap_realm_screen.empty_field.error";
    private LDAPManagementAuthConfig config;
    private final JTextField realmNameField = createTextField("ldap.security.realm");
    private final JTextField baseDNField = createTextField("dc=myCompany,dc=org");
    private final JComboBox<String> filterTypeField = createDropdown(LDAPManagementAuthConfig.FilterType.getLabels());
    private final JTextField filterField = createTextField("userName");
    private final JComboBox<String> recursiveSearchField = createDropdown(new String[] {"ldap_realm_screen.recursive_search.no", "ldap_realm_screen.recursive_search.yes"});
    private JButton testButton = createButton(LDAP_REALM_SCREEN_TEST_SEARCH_BUTTON, this::validateSearch);

    public LDAPSecurityRealmScreen(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_REALM_SCREEN_DESCRIPTION), c);
        c.gridy++;

        c.gridwidth = 1;

        addField(content, c, LDAP_REALM_SCREEN_REALM_NAME_LABEL, realmNameField);

        addField(content, c, LDAP_REALM_SCREEN_BASE_DN_LABEL, baseDNField);

        addField(content, c, LDAP_REALM_SCREEN_FILTER_TYPE_LABEL, filterTypeField);

        addField(content, c, LDAP_REALM_SCREEN_USERNAME_FILTER_LABEL, filterField);

        addField(content, c, LDAP_REALM_SCREEN_RECURSIVE_SEARCH_LABEL, recursiveSearchField);

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

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

        return content;
    }

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

    private LDAPManagementAuthConfig populateConfig() {
        config.setRealmName(UiResources.readTextValue(realmNameField));
        config.setBaseDN(UiResources.readTextValue(baseDNField));

        config.setFilterType(LDAPManagementAuthConfig.FilterType.values()[filterTypeField.getSelectedIndex()]);
        config.setFilter(UiResources.readTextValue(filterField));
        config.setRecursive(recursiveSearchField.getSelectedIndex() == 1);

        return config;
    }

    @Override
    public void load(InstallationData installationData) {
        config = installationData.getConfig(LDAPManagementAuthConfig.class);
    }

    @Override
    public ValidationResult validate() {
        if (!validateNonEmpty(UiResources.readTextValue(realmNameField)) ||
            !validateNonEmpty(UiResources.readTextValue(baseDNField)) ||
            !validateNonEmpty(UiResources.readTextValue(filterField))) {
            return ValidationResult.error(langUtils.getString(LDAP_REALM_SCREEN_EMPTY_FIELD_ERROR));
        }

        config = populateConfig();

        return ValidationResult.ok();
    }

    @Override
    public void record(InstallationData installationData) {
        installationData.addPostInstallTask(PostInstallTask.SetupLDAPManagementAuth);


        final HashMap<String, String> attrs = new HashMap<>();
        attrs.put(langUtils.getString(LDAPConnectionScreen.LDAP_SCREEN_LABEL_CONNECTION_NAME), config.getConnection());
        attrs.put(langUtils.getString(LDAPConnectionScreen.LDAP_SCREEN_LABEL_DIRECTORY_SERVER), config.getUrl());
        attrs.put(langUtils.getString(LDAPConnectionScreen.LDAP_SCREEN_LABEL_DISTINGUISHED_NAME), config.getDn());

        attrs.put(langUtils.getString(LDAP_REALM_SCREEN_REALM_NAME_LABEL), config.getRealmName());
        attrs.put(langUtils.getString(LDAP_REALM_SCREEN_BASE_DN_LABEL), config.getBaseDN());
        attrs.put(langUtils.getString(LDAP_REALM_SCREEN_FILTER_TYPE_LABEL), langUtils.getString(config.getFilterType().getKey()));
        attrs.put(langUtils.getString(LDAP_REALM_SCREEN_USERNAME_FILTER_LABEL), config.getFilter());
        attrs.put(langUtils.getString(LDAP_REALM_SCREEN_RECURSIVE_SEARCH_LABEL), "" + config.isRecursive());
        installationData.updateSummary(LDAPSecurityRealmScreen.NAME, langUtils.getString(ConfigureRuntimeEnvironmentScreen.LDAP_AUTHENTICATION_KEY), attrs);
    }

    @Override
    public void rollback(InstallationData installationData) {
        // LDAPConnectionScreen will remove config
        installationData.removePostInstallTask(PostInstallTask.SetupLDAPManagementAuth);
    }

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

    private void validateSearch(ActionEvent e) {
        config = populateConfig();

        final ValidationResult result = new SearchDnValidator(langUtils).validateData(config);
        if (result.getResult() != ValidationResult.Result.OK) {
            InstallerDialogs.showErrorMessage(result.getMessage(), langUtils, null);
        }
    }
}
