/*
 * 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.bugtracking.tasks;

import java.awt.event.ActionEvent;
import java.util.List;
import java.util.MissingResourceException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingUtilities;
import org.netbeans.modules.bugtracking.commons.LinkButton;
import org.netbeans.modules.bugtracking.tasks.dashboard.DashboardViewer;
import org.netbeans.modules.bugtracking.tasks.dashboard.TaskNode;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;

/**
 *
 * @author jpeska
 */
public class CategoryPicker extends javax.swing.JPanel {

    private List<Category> categories;
    private final Action newCatAction;
    private CategoryComboListener listener;
    private final TaskNode[] taskNodes;
    private final DashboardViewer dashboardViewer = DashboardViewer.getInstance();

    /**
     * Creates new form CategoryPicker
     */
    public CategoryPicker(TaskNode... taskNodes) {
        this.taskNodes = taskNodes;
        newCatAction = getNewCatAction();
        initComponents();
        initCombo();
    }

    public Category getChosenCategory() {
        return categories.get(cbCategory.getSelectedIndex());
    }

    public void setCategoryListener(CategoryComboListener listener) {
        this.listener = listener;
    }

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

        jLabel1 = new javax.swing.JLabel();
        cbCategory = new javax.swing.JComboBox();
        btnNewCat = new LinkButton(newCatAction);

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

        btnNewCat.setText(org.openide.util.NbBundle.getMessage(CategoryPicker.class, "LBL_New")); // 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(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbCategory, 0, 200, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnNewCat)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNewCat))
                .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.JButton btnNewCat;
    private javax.swing.JComboBox cbCategory;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables

    private Action getNewCatAction() {
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Category category = DashboardTopComponent.findInstance().createCategory();
                if (category == null) {
                    return;
                }
                categories.add(category);
                initCombo();
                cbCategory.setSelectedItem(category.getName());
            }
        };
    }

    private void initCombo() {
        cbCategory.setModel(new DefaultComboBoxModel(new String[]{NbBundle.getMessage(CategoryPicker.class, "LBL_Loading")}));
        RequestProcessor.getDefault().post(new Runnable() {
            @Override
            public void run() {
                initCategories();
            }
        });
    }

    private void initCategories() throws MissingResourceException {
        this.categories = dashboardViewer.preloadCategories();
        if (taskNodes.length == 1) {
            TaskNode taskNode = taskNodes[0];
            if (taskNode.isCategorized()) {
                categories.remove(taskNode.getCategory());
            }
        }
        String[] names = new String[categories.size()];
        //names[0] = NbBundle.getMessage(CategoryPicker.class, "LBL_NoCategory"); //NOI18N
        int i = 0;
        boolean categoryAvailable = true;
        for (Category category : categories) {
            names[i++] = category.getName();
        }
        if (categories.isEmpty()) {
            names = new String[]{NbBundle.getMessage(CategoryPicker.class, "LBL_NoCategoryAvailable")};
            categoryAvailable = false;
        }
        final String[] namesF = names;
        final boolean categoryAvailableF = categoryAvailable;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                cbCategory.setModel(new DefaultComboBoxModel(namesF));
                if (listener != null) {
                    listener.comboItemsChanged(categoryAvailableF);
                }
            }
        });
    }

    public interface CategoryComboListener {
        public void comboItemsChanged(boolean categoryAvailable);
    }
}
