package org.netbeans.gradle.project.java.properties;

import java.net.URL;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import org.netbeans.gradle.project.NbStrings;
import org.netbeans.gradle.project.api.config.ActiveSettingsQuery;
import org.netbeans.gradle.project.api.config.PropertyReference;
import org.netbeans.gradle.project.api.config.ui.CustomizerCategoryId;
import org.netbeans.gradle.project.api.config.ui.ProfileBasedSettingsCategory;
import org.netbeans.gradle.project.api.config.ui.ProfileEditor;
import org.netbeans.gradle.project.api.config.ui.ProfileEditorFactory;
import org.netbeans.gradle.project.api.config.ui.ProfileInfo;
import org.netbeans.gradle.project.api.config.ui.StoredSettings;
import org.netbeans.gradle.project.properties.global.GlobalSettingsPage;
import org.netbeans.gradle.project.util.NbFileUtils;
import org.netbeans.gradle.project.util.NbGuiUtils;

@SuppressWarnings("serial")
public class JavaModulesPanel extends javax.swing.JPanel implements ProfileEditorFactory {
    private static final URL HELP_URL = NbFileUtils.getSafeURL("https://github.com/kelemen/netbeans-gradle-project/wiki/Java-Modules");

    private final boolean allowInherit;

    public JavaModulesPanel(boolean allowInherit) {
        this.allowInherit = allowInherit;

        initComponents();

        if (!allowInherit) {
            jAllowModulesInherit.setVisible(false);
            jAllowModulesInherit.setSelected(false);
        }

        setupEnableDisable();
    }

    private void setupEnableDisable() {
        setupInheritCheck(jAllowModulesInherit, jAllowModules);
    }

    private static void setupInheritCheck(JCheckBox inheritCheck, JComponent... components) {
        NbGuiUtils.enableBasedOnCheck(inheritCheck, false, components);
    }

    private <Value> Value setInheritAndGetValue(
            Value value,
            PropertyReference<? extends Value> valueWithFallbacks,
            JCheckBox inheritCheck) {
        inheritCheck.setSelected(allowInherit && value == null);
        return value != null ? value : valueWithFallbacks.getActiveValue();
    }

    private static CustomizerCategoryId getCategoryId() {
        return new CustomizerCategoryId(JavaModulesPanel.class.getName(), NbStrings.getSettingsCategoryJavaModules());
    }

    public static ProfileBasedSettingsCategory createCustomizer(boolean allowInherit) {
        return new ProfileBasedSettingsCategory(getCategoryId(), () -> JavaModulesPanel.createSettingsPage(allowInherit));
    }

    public static GlobalSettingsPage createSettingsPage(boolean allowInherit) {
        GlobalSettingsPage.Builder result = new GlobalSettingsPage.Builder(new JavaModulesPanel(allowInherit));
        result.setHelpUrl(HELP_URL);
        return result.create();
    }

    @Override
    public ProfileEditor startEditingProfile(ProfileInfo profileInfo, ActiveSettingsQuery profileQuery) {
        return new PropertyRefs(profileQuery);
    }

    private final class PropertyRefs implements ProfileEditor {
        private final PropertyReference<Boolean> allowModulesRef;

        public PropertyRefs(ActiveSettingsQuery settingsQuery) {
            this.allowModulesRef = JavaProjectProperties.allowModules(settingsQuery);
        }

        @Override
        public StoredSettings readFromSettings() {
            return new StoredSettingsImpl(this);
        }

        @Override
        public StoredSettings readFromGui() {
            return new StoredSettingsImpl(this, JavaModulesPanel.this);
        }
    }

    private final class StoredSettingsImpl implements StoredSettings {
        private final PropertyRefs properties;
        private final Boolean allowModules;

        public StoredSettingsImpl(PropertyRefs properties) {
            this.properties = properties;
            this.allowModules = properties.allowModulesRef.tryGetValueWithoutFallback();
        }

        public StoredSettingsImpl(PropertyRefs properties, JavaModulesPanel panel) {
            this.properties = properties;

            this.allowModules = allowInherit && panel.jAllowModulesInherit.isSelected()
                    ? null
                    : panel.jAllowModules.isSelected();
        }

        @Override
        public void displaySettings() {
            Boolean activeAllowModules = setInheritAndGetValue(allowModules, properties.allowModulesRef, jAllowModulesInherit);
            jAllowModules.setSelected(activeAllowModules);
        }

        @Override
        public void saveSettings() {
            properties.allowModulesRef.setValue(allowModules);
        }
    }


    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jAllowModules = new javax.swing.JCheckBox();
        jAllowModulesInherit = new javax.swing.JCheckBox();

        org.openide.awt.Mnemonics.setLocalizedText(jAllowModules, org.openide.util.NbBundle.getMessage(JavaModulesPanel.class, "JavaModulesPanel.jAllowModules.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jAllowModulesInherit, org.openide.util.NbBundle.getMessage(JavaModulesPanel.class, "JavaModulesPanel.jAllowModulesInherit.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jAllowModules, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jAllowModulesInherit)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jAllowModules)
                    .addComponent(jAllowModulesInherit))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox jAllowModules;
    private javax.swing.JCheckBox jAllowModulesInherit;
    // End of variables declaration//GEN-END:variables
}
