package org.jboss.installer.screens;

import org.jboss.installer.ArgumentsParser;
import org.jboss.installer.auto.AutomaticInstallationParsingException;
import org.jboss.installer.auto.InstallationDataSerializer;
import org.jboss.installer.common.FontResources;
import org.jboss.installer.common.InstallerDialogs;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.InstallationData;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class InstallationCompleteScreen extends DefaultScreen {

    public static final String NAME = "InstallationCompleteScreen";
    public static final String TITLE_KEY = "installation_complete_screen.title";
    private static final String SIDE_NAV_KEY = "installation_complete_screen.side_nav";
    public static final String TARGET_TEXT_KEY = "installation_complete.target_text";
    public static final String GENERATE_SCRIPT_KEY = "installation_complete_screen.generate_script";
    public static final String GENERATE_SCRIPT_COMPLETED_KEY = "installation_complete_screen.generate_script_completed";
    public static final String XML_FILTER_KEY = "installation_complete_screen.xml_filter";
    public static final String INSTALLATION_SCRIPT_EXTENSION = "xml";
    private InstallationData installationData;


    public InstallationCompleteScreen(LanguageUtils langUtils) {
        super(langUtils);
    }

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

    @Override
    public String getSideNavName() {
        return langUtils.getString(SIDE_NAV_KEY);
    }

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

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

        c.insets = FIELD_ROW_INSET;
        content.add(createSubHeadingLabel(TARGET_TEXT_KEY), c);
        c.gridy++;

        c.insets = SUBSECTION_INSET;
        content.add(createFieldLabel(installationData.getTargetFolder().toString() + "/uninstaller", false), c);
        c.gridy++;

        c.insets = FIELD_ROW_INSET;
        content.add(createSubHeadingLabel("installation_complete_sceen.auto_header"), c);
        c.gridy++;

        c.insets = SUBSECTION_INSET;
        content.add(createDescription("installation_complete_sceen.auto_desc"), c);
        c.gridy++;

        c.insets = SUBSECTION_INSET;
        final JLabel usageLabel = createFieldLabel(ArgumentsParser.COMMAND_SYNTAX_EXAMPLE, false);
        usageLabel.setFont(FontResources.getMonospaceFont());
        content.add(usageLabel, c);
        c.gridy++;

        c.insets = FIELD_ROW_INSET;
        c.fill = GridBagConstraints.NONE;
        JButton generateScriptButton = createButton(GENERATE_SCRIPT_KEY, e -> {
            generateAutoInstallScript(content, (JButton) e.getSource());
        });
        content.add(generateScriptButton, c);
        c.gridy++;
        addToolTip(generateScriptButton, GENERATE_SCRIPT_KEY + ".tooltip");

        c.weighty = 1;
        content.add(Box.createVerticalBox(), c);

        return content;
    }

    private void generateAutoInstallScript(JPanel content, JButton generateScriptButton) {
        final JFileChooser fileBrowser = new JFileChooser(installationData.getTargetFolder().toFile());
        fileBrowser.setDialogType(JFileChooser.SAVE_DIALOG);
        fileBrowser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        final FileNameExtensionFilter xmlFileExtension = new FileNameExtensionFilter(langUtils.getString(XML_FILTER_KEY), INSTALLATION_SCRIPT_EXTENSION);
        fileBrowser.setFileFilter(xmlFileExtension);
        int returnVal = fileBrowser.showSaveDialog(content);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File selectedFile = getSelectedFile(fileBrowser, xmlFileExtension);

            Path target = Paths.get(selectedFile.getPath()).toAbsolutePath();

            try (InstallationDataSerializer serializer = new InstallationDataSerializer(langUtils)) {
                serializer.serialize(installationData, target);
            } catch (AutomaticInstallationParsingException | IOException ex) {
                InstallerDialogs.showErrorMessage(ex.getMessage(), langUtils, content);
            }
            generateScriptButton.setText(langUtils.getString(GENERATE_SCRIPT_COMPLETED_KEY));
            generateScriptButton.setEnabled(false);
        }
    }

    private File getSelectedFile(JFileChooser fileBrowser, FileNameExtensionFilter xmlFileExtension) {
        File selectedFile = fileBrowser.getSelectedFile();
        if (!xmlFileExtension.accept(selectedFile)) {
            String newName = selectedFile.getName() + "." + INSTALLATION_SCRIPT_EXTENSION;
            selectedFile = new File(selectedFile.getParent(), newName);
        }
        return selectedFile;
    }

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