package org.jboss.installer.screens.jsf;

import org.jboss.installer.common.UiResources;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.MnemonicUtils;
import org.jboss.installer.core.ValidationResult;
import org.jboss.installer.postinstall.task.JsfLibraryTask;

import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.nio.file.Path;

import static org.jboss.installer.screens.DefaultScreen.FIELD_ROW_INSET;
import static org.jboss.installer.screens.JSFInstallScreen.FULL_COLUMN_WIDTH;

public class ChannelPanel extends JPanel {

    // disable option to use existing channel - this is an advanced operation, for now we decided not to expose it
    // through GUI installer. Leaving the code in case the decision is changed in future releases.
    protected static final boolean EXISTING_CHANNEL_ENABLED = false;
    private ChannelOptionsPanel channelOptionsPanel;

    private CreateNewChannelPanel newChannelPanel;
    private ExistingChannelPanel existingChannelPanel;

    public ChannelPanel(LanguageUtils langUtils, MnemonicUtils mnemonicUtils, Path installationDir) {
        super(new GridBagLayout());

        this.channelOptionsPanel = new ChannelOptionsPanel();
        this.newChannelPanel = new CreateNewChannelPanel(langUtils, mnemonicUtils, installationDir);
        this.existingChannelPanel = new ExistingChannelPanel(langUtils, mnemonicUtils);

        final GridBagConstraints c = UiResources.initializeConstraints();

        c.gridwidth = FULL_COLUMN_WIDTH;
        c.insets = FIELD_ROW_INSET;
        this.add(channelOptionsPanel, c);
        channelOptionsPanel.setVisible(EXISTING_CHANNEL_ENABLED);
        c.gridy++;

        newChannelPanel.setVisible(channelOptionsPanel.getSelected() == ChannelOptionsPanel.Options.CREATE_CHANNEL);
        this.add(newChannelPanel, c);
        c.gridy++;

        existingChannelPanel.setVisible(channelOptionsPanel.getSelected() == ChannelOptionsPanel.Options.EXISTING_CHANNEL);
        this.add(existingChannelPanel, c);

        this.channelOptionsPanel.registerSwitch(newChannelPanel, existingChannelPanel);
    }


    public void populateConfig(JsfLibraryTask.Config config) {
        if (channelOptionsPanel.getSelected() == ChannelOptionsPanel.Options.CREATE_CHANNEL) {
            newChannelPanel.populateConfig(config);
        } else {
            existingChannelPanel.populateConfig(config);
        }
    }


    public ValidationResult validateInput() {
        if (channelOptionsPanel.getSelected() == ChannelOptionsPanel.Options.CREATE_CHANNEL) {
            return newChannelPanel.validateInput();
        } else {
            return existingChannelPanel.validateInput();
        }
    }
}
