/*
 * #%L
 * gitools-ui-app
 * %%
 * Copyright (C) 2013 Universitat Pompeu Fabra - Biomedical Genomics group
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package org.gitools.ui.wizard.common;

import org.gitools.ui.utils.DocumentChangeListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @noinspection ALL
 */
public class FilteredListPanel extends javax.swing.JPanel {

    private static final long serialVersionUID = -513470999308628358L;

    private String lastFilterText = "";
    private Object[] listData;

    /**
     * Creates new form BiomartFilterListPanel
     */
    public FilteredListPanel() {
        initComponents();
        initEvents();
    }

    /**
     * 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        filterField = new javax.swing.JTextField();
        clearBtn = new javax.swing.JButton();

        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(list);

        clearBtn.setText("Clear");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE).addGroup(layout.createSequentialGroup().addComponent(filterField, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(clearBtn))).addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(clearBtn).addComponent(filterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE).addContainerGap()));
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearBtn;
    private javax.swing.JTextField filterField;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JList list;
    // End of variables declaration//GEN-END:variables

    private void initEvents() {
        filterField.getDocument().addDocumentListener(new DocumentChangeListener() {
            @Override
            protected void update(DocumentEvent e) {
                updateFilter();
            }
        });

        clearBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                filterField.setText("");
                filterField.requestFocusInWindow();
            }
        });

        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                selectionChanged();
            }
        });
    }

    private void updateFilter() {
        final String filterText = getFilterText();

        clearBtn.setEnabled(!filterText.isEmpty());

        if (!filterText.equalsIgnoreCase(lastFilterText)) {
            lastFilterText = filterText;
            list.setModel(createListModel(listData, getFilterText()));
        }
    }

    public String getFilterText() {
        return filterField.getText();
    }

    public void resetFilterText() {
        filterField.setText("");
        filterField.requestFocusInWindow();
    }

    @NotNull
    private ListModel createListModel(@NotNull Object[] listData, @Nullable String filterText) {
        final DefaultListModel model = new DefaultListModel();

        if (filterText != null && !filterText.isEmpty()) {
            final String filter = filterText.toLowerCase();
            for (Object dataObject : listData) {
                String dataText = dataObject.toString().toLowerCase();
                if (dataText.contains(filter)) {
                    model.addElement(dataObject);
                }
            }
        } else {
            for (Object dataObject : listData)
                model.addElement(dataObject);
        }

        return model;
    }

    protected void selectionChanged() {
    }

    public void setListData(@NotNull Object[] listData) {
        this.listData = listData;
        ListModel model = createListModel(listData, getFilterText());

        list.setModel(model);
        selectionChanged();

        filterField.requestFocusInWindow();
    }

    /* Set list selection mode.
     *
     * The following list describes the accepted selection modes:
     * <ul>
     * <li>{@code ListSelectionModel.SINGLE_SELECTION} -
     *   Only one list index can be selected at a time. In this mode,
     *   {@code setSelectionInterval} and {@code addSelectionInterval} are
     *   equivalent, both replacing the current selection with the index
     *   represented by the second argument (the "lead").
     * <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
     *   Only one contiguous interval can be selected at a time.
     *   In this mode, {@code addSelectionInterval} behaves like
     *   {@code setSelectionInterval} (replacing the current selection},
     *   unless the given interval is immediately adjacent to or overlaps
     *   the existing selection, and can be used to grow the selection.
     * <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
     *   In this mode, there's no restriction on what can be selected.
     *   This mode is the default.
     * </ul>
     */
    public void setSelectionMode(int mode) {
        list.setSelectionMode(mode);
    }

    public Object getSelectedValue() {
        return list.getSelectedValue();
    }

    public void setSElectedValue(Object o) {
        list.setSelectedValue(o, true);
    }

    public Object[] getSelectedValues() {
        return list.getSelectedValues();
    }
}
