/*
 * 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.FileChooserPanel;
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.CredentialStoreInstallTask;
import org.jboss.installer.validators.CredentialStoreValidator;
import org.jboss.installer.validators.PasswordEqualityValidator;
import org.jboss.installer.validators.PathValidator;

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.nio.file.Path;

import static javax.swing.JFileChooser.FILES_ONLY;

public class CredentialStoreScreen extends DefaultScreen{

    public static final String NAME = "PasswordVaultScreen";
    public static final String TITLE_KEY="credential_store.title";
    public static final String CREDENTIAL_STORE_DESCRIPTION = "credential_store.description";
    public static final String CREDENTIAL_STORE_DESCRIPTION_CTD = "credential_store.description2";
    public static final String CREDENTIAL_STORE_STORE_NAME_LABEL = "credential_store.store_name";
    public static final String DEFAULT_STORE_NAME = "local-credential-store";
    public static final String CREDENTIAL_STORE_PASSWORD_LABEL = "credential_store.password";
    public static final String CREDENTIAL_STORE_PASSWORD_CONFIRM_LABEL = "credential_store.password_confirm";
    public static final String CREDENTIAL_STORE_LOCATION_LABEL = "credential_store.location";
    public static final String DEFAULT_CRED_STORE_FILENAME = "credential.store";
    private final JTextField storeNameField = createTextField(DEFAULT_STORE_NAME);
    private final JPasswordField passwordConfirmField = createPasswordField();
    private final JPasswordField passwordField = createPasswordField();
    private FileChooserPanel locationChooser;
    private CredentialStoreInstallTask action = new CredentialStoreInstallTask();
    private Path targetFolder;

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

    @Override
    public void load(InstallationData installationData) {
        targetFolder = installationData.getTargetFolder();
    }

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

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

    @Override
    public JPanel getContent() {

        if (locationChooser == null) {
            locationChooser = FileChooserPanel.builder(langUtils, FILES_ONLY, mnemonicUtils).baseFolder(targetFolder.resolve(DEFAULT_CRED_STORE_FILENAME).toString()).build();
        }

        JPanel content = new JPanel(new GridBagLayout());
        final GridBagConstraints c = initializeConstraints();
        c.gridwidth = 2;

        c.insets = DESCRIPTION_INSET;
        content.add(createDescription(CREDENTIAL_STORE_DESCRIPTION), c);


        c.gridwidth = 1;
        addField(content, c, CREDENTIAL_STORE_STORE_NAME_LABEL, storeNameField);

        addField(content, c, CREDENTIAL_STORE_PASSWORD_LABEL, passwordField);

        addField(content, c, CREDENTIAL_STORE_PASSWORD_CONFIRM_LABEL, passwordConfirmField);

        c.gridy++;
        content.add(createFieldLabel(CREDENTIAL_STORE_LOCATION_LABEL), c);

        c.gridwidth = 2;
        c.gridy++;
        content.add(locationChooser, c);
        addToolTip(locationChooser, CREDENTIAL_STORE_LOCATION_LABEL+".tooltip");

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

        return content;
    }

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

    @Override
    public ValidationResult validate() {
        ValidationResult res = new PasswordEqualityValidator(langUtils).validate(passwordField.getText(), passwordConfirmField.getText());
        if (res.getResult() != ValidationResult.Result.OK) {
            return res;
        }

        final CredentialStoreInstallTask.Config config;
        try {
            config = new CredentialStoreInstallTask.Config(UiResources.readTextValue(storeNameField),
                    null, locationChooser.asPath(), passwordField.getText());
        } catch (FileChooserPanel.InvalidPathException e) {
            return PathValidator.newInstance("generic", langUtils).validate(e.getPath());
        }
        res = new CredentialStoreValidator(langUtils, targetFolder).validate(config);
        if (res.getResult() != ValidationResult.Result.OK) {
            return res;
        }

        return super.validate();
    }

    @Override
    public void record(InstallationData installationData) {
        final CredentialStoreInstallTask.Config config;
        try {
            config = new CredentialStoreInstallTask.Config(UiResources.readTextValue(storeNameField),
                    null, locationChooser.asPath(), passwordField.getText());
        } catch (FileChooserPanel.InvalidPathException e) {
            // was handled in validate step
            throw new RuntimeException(e);
        }
        installationData.putConfig(config);
        installationData.addPostInstallTask(action);
    }

    @Override
    public void rollback(InstallationData installationData) {
        installationData.removeConfig(CredentialStoreInstallTask.Config.class);
        installationData.removePostInstallTask(action);
        // 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("");
    }
}
