/*
 * Copyright 2021 Red Hat, Inc. and/or its affiliates
 * and other 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.apache.commons.lang3.StringUtils;
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.ScreenManager;
import org.jboss.installer.core.ValidationResult;
import org.jboss.installer.postinstall.task.QuickstartsTask;
import org.jboss.installer.validators.WritableFolderValidator;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.URL;
import java.nio.file.Paths;

import static javax.swing.JFileChooser.DIRECTORIES_ONLY;
import static org.jboss.installer.Installer.EAP_VERSION;

public class QuickstartsScreen extends DefaultScreen{

    public static final String NAME = "QuickstartsScreen";
    public static final String TITLE_KEY = "quickstarts.title";
    public static final String DESCRIPTION_KEY = "quickstarts.description";
    public static final String SELECT_REPOSITORY_PATH_KEY = "quickstarts.select_path";
    public static final String SELECT_GITHUB_REPO_KEY = "quickstarts.select_github_repo";
    public static final String SELECT_GITHUB_BRANCH_KEY = "quickstarts.select_github_branch";
    public static final String DEFAULT_QUICKSTARTS_GITHUB_REPO = "https://github.com/jboss-developer/jboss-eap-quickstarts";
    public static final String DEFAULT_QUICKSTARTS_GITHUB_BRANCH = "8.0.x"; // TODO this would be extracted from eap version when there is an applicable EAP 8 branch.
    private static final String QUICKSTART_GITHUB_REPOSITORY_EMPTY_ERROR = "quickstarts.github.repository.empty.error";
    private static final String QUICKSTART_GITHUB_REPOSITORY_INVALID_ERROR = "quickstarts.github.repository.invalid.error";
    private static final String QUICKSTART_GITHUB_BRANCH_EMPTY_ERROR = "quickstarts.github.branch.empty.error";
    private final JTextArea description = createDescription(DESCRIPTION_KEY);
    private final JLabel installationPathLabel = createFieldLabel(SELECT_REPOSITORY_PATH_KEY);
    private final FileChooserPanel installationFolder = FileChooserPanel.builder(langUtils, DIRECTORIES_ONLY, mnemonicUtils)
            .baseFolder(Paths.get(HOME_DIR, "EAP-" + EAP_VERSION, "jboss-eap-quickstarts").toString()).build();
    private final WritableFolderValidator validator;
    private final JTextField quickStartsGithubRepoTextField = createTextField(DEFAULT_QUICKSTARTS_GITHUB_REPO);
    private final JTextField quickStartsGithubBranchTextField = createTextField(DEFAULT_QUICKSTARTS_GITHUB_BRANCH);

    public QuickstartsScreen(Screen parent, LanguageUtils langUtils, boolean isActive) {
        super(parent, langUtils, isActive);
        validator = new WritableFolderValidator("quickstarts", langUtils);
    }

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

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

    @Override
    public JPanel getContent() {
        JPanel content = new JPanel();
        content.setLayout(new GridBagLayout());
        GridBagConstraints c = UiResources.initializeConstraints();
        c.gridwidth = 2;
        c.insets = FIELD_ROW_INSET;

        content.add(description, c);
        c.gridy++;

        content.add(installationPathLabel, c);
        addToolTip(installationPathLabel, SELECT_REPOSITORY_PATH_KEY + ".tooltip");
        c.gridy++;

        content.add(installationFolder, c);
        addToolTip(installationFolder, SELECT_REPOSITORY_PATH_KEY + ".tooltip");
        c.gridy++;

        c.gridwidth = 1;
        addField(content, c, SELECT_GITHUB_REPO_KEY, quickStartsGithubRepoTextField);
        addField(content, c, SELECT_GITHUB_BRANCH_KEY, quickStartsGithubBranchTextField);
        c.gridy++;

        fillEmptySpace(content, c);
        return content;
    }

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

    @Override
    public void load(InstallationData installationData, ScreenManager screenManager) {
        screenManager.setScreenActivity(QuickstartsMavenRepositorySetupScreen.NAME, false);
    }

    @Override
    public ValidationResult validate() {
        ValidationResult res = validator.validate(installationFolder.getText(), false);
        if (res.getResult() != ValidationResult.Result.OK) {
            return res;
        }
        if (StringUtils.isEmpty(UiResources.readTextValue(quickStartsGithubRepoTextField))) {
            return ValidationResult.error(langUtils.getString(QUICKSTART_GITHUB_REPOSITORY_EMPTY_ERROR));
        }
        if (!isValidURL(UiResources.readTextValue(quickStartsGithubRepoTextField))) {
            return ValidationResult.error(langUtils.getString(QUICKSTART_GITHUB_REPOSITORY_INVALID_ERROR));
        }
        if (StringUtils.isEmpty(UiResources.readTextValue(quickStartsGithubBranchTextField))) {
            return ValidationResult.error(langUtils.getString(QUICKSTART_GITHUB_BRANCH_EMPTY_ERROR));
        }
        return ValidationResult.ok();
    }

    private boolean isValidURL(String url) {
        try {
            new URL(url);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void record(InstallationData installationData, ScreenManager screenManager) {
        screenManager.setScreenActivity(QuickstartsMavenRepositorySetupScreen.NAME, true);
        QuickstartsTask.Config config = new QuickstartsTask.Config();
        config.setQuickstartsTargetFolder(installationFolder.getText());
        config.setQuickstartsGithubRepo(UiResources.readTextValue(quickStartsGithubRepoTextField));
        config.setQuickstartsGithubBranch(UiResources.readTextValue(quickStartsGithubBranchTextField));
        installationData.putConfig(config);
    }

    @Override
    public void rollback(InstallationData installationData) {
        installationData.removeConfig(QuickstartsTask.Config.class);
    }
}