/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.netbeans.modules.java.hints;

import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.prefs.Preferences;

/**
 *
 * @author rsvitanic
 */
public class LoggerHintsCustomizer extends javax.swing.JPanel {

    public static final String CUSTOM_LOGGERS_ENABLED = "custom-loggers";
    public static final String CUSTOM_LOGGERS = "custom-loggers-list";
    private Preferences p;
    private final List<String> customLoggersList = new ArrayList<>();

    public LoggerHintsCustomizer(Preferences p) {
        initComponents();
        this.p = p;
        loggersCheckbox.setSelected(p.getBoolean(CUSTOM_LOGGERS_ENABLED, false));
        p.putBoolean(CUSTOM_LOGGERS_ENABLED, loggersCheckbox.isSelected());
        enableDisablePanel(loggersCheckbox.isSelected());
        List<String> loadedValues = loadLoggersFromPrefs();
        if (loadedValues != null) {
            customLoggersList.addAll(loadedValues);
        }
        customLoggers.setListData(customLoggersList.toArray());
        btnRemove.setEnabled(loggersCheckbox.isSelected() && !customLoggersList.isEmpty());
    }

    private void enableDisablePanel(boolean enabled) {
        loggersPanel.setEnabled(enabled);
        Component[] components = loggersPanel.getComponents();
        for (Component c : components) {
            if (!c.equals(btnRemove)) {
                c.setEnabled(enabled);
            }
        }
        btnRemove.setEnabled(enabled && !customLoggersList.isEmpty());
        loggersScrollPane.getViewport().getView().setEnabled(enabled);
    }

    /**
     * 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() {

        loggersCheckbox = new javax.swing.JCheckBox();
        loggersPanel = new javax.swing.JPanel();
        customLogClass = new javax.swing.JTextField();
        loggersScrollPane = new javax.swing.JScrollPane();
        customLoggers = new javax.swing.JList();
        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        lblInstructions = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(360, 150));

        org.openide.awt.Mnemonics.setLocalizedText(loggersCheckbox, org.openide.util.NbBundle.getMessage(LoggerHintsCustomizer.class, "LoggerHintsCustomizer.loggersCheckbox.text")); // NOI18N
        loggersCheckbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loggersCheckboxActionPerformed(evt);
            }
        });

        loggersPanel.setPreferredSize(new java.awt.Dimension(360, 121));

        customLogClass.setText(org.openide.util.NbBundle.getMessage(LoggerHintsCustomizer.class, "LoggerHintsCustomizer.customLogClass.text")); // NOI18N

        customLoggers.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        loggersScrollPane.setViewportView(customLoggers);

        org.openide.awt.Mnemonics.setLocalizedText(btnAdd, org.openide.util.NbBundle.getMessage(LoggerHintsCustomizer.class, "LoggerHintsCustomizer.btnAdd.text")); // NOI18N
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(btnRemove, org.openide.util.NbBundle.getMessage(LoggerHintsCustomizer.class, "LoggerHintsCustomizer.btnRemove.text")); // NOI18N
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

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

        javax.swing.GroupLayout loggersPanelLayout = new javax.swing.GroupLayout(loggersPanel);
        loggersPanel.setLayout(loggersPanelLayout);
        loggersPanelLayout.setHorizontalGroup(
            loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loggersPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(loggersPanelLayout.createSequentialGroup()
                        .addComponent(lblInstructions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(82, 82, 82))
                    .addGroup(loggersPanelLayout.createSequentialGroup()
                        .addGroup(loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(customLogClass)
                            .addComponent(loggersScrollPane))
                        .addGap(11, 11, 11)
                        .addGroup(loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnRemove)))))
        );
        loggersPanelLayout.setVerticalGroup(
            loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loggersPanelLayout.createSequentialGroup()
                .addGroup(loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(customLogClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblInstructions)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(loggersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(loggersScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnRemove))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(loggersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(loggersCheckbox)
                .addContainerGap(115, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(loggersCheckbox)
                .addGap(3, 3, 3)
                .addComponent(loggersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void loggersCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loggersCheckboxActionPerformed
        enableDisablePanel(loggersCheckbox.isSelected());
        p.putBoolean(CUSTOM_LOGGERS_ENABLED, loggersCheckbox.isSelected());
    }//GEN-LAST:event_loggersCheckboxActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        if (customLogClass.getText().matches("(\\w+\\.?)+")) {
            if (customLoggersList.contains(customLogClass.getText())) {
                customLogClass.setText("");
                return;
            }
            customLoggersList.add(customLogClass.getText().trim());
            Collections.sort(customLoggersList);
            customLogClass.setText("");
            writeSettingsToProperties();
            customLoggers.setListData(customLoggersList.toArray());
            btnRemove.setEnabled(!customLoggersList.isEmpty());
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        customLoggersList.remove((String) customLoggers.getSelectedValue());
        writeSettingsToProperties();
        customLoggers.setListData(customLoggersList.toArray());
        btnRemove.setEnabled(!customLoggersList.isEmpty());
    }//GEN-LAST:event_btnRemoveActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnRemove;
    private javax.swing.JTextField customLogClass;
    private javax.swing.JList customLoggers;
    private javax.swing.JLabel lblInstructions;
    private javax.swing.JCheckBox loggersCheckbox;
    private javax.swing.JPanel loggersPanel;
    private javax.swing.JScrollPane loggersScrollPane;
    // End of variables declaration//GEN-END:variables

    private void writeSettingsToProperties() {
        StringBuilder sb = new StringBuilder();
        for (String s : customLoggersList) {
            sb.append(s);
            if (customLoggersList.indexOf(s) != (customLoggersList.size() - 1)) {
                sb.append(",");
            }
        }
        p.put(CUSTOM_LOGGERS, sb.toString());
    }

    private List<String> loadLoggersFromPrefs() {
        String loggers = p.get(CUSTOM_LOGGERS, null);
        if (loggers == null || loggers.equals("")) {
            p.put(CUSTOM_LOGGERS, "");
            return null;
        }
        p.put(CUSTOM_LOGGERS, loggers);
        List<String> loggersList = new ArrayList<>();
        String[] tmpArray = loggers.split(",");
        loggersList.addAll(Arrays.asList(tmpArray));
        return loggersList;
    }
}
