package kiyut.sketsa.modules.symbollibrary;


import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;
import kiyut.sketsa.api.symbollibrary.Symbol;

/**
 * The implementation of SymbolListModel
 *
 * @author Kiyut
 */
public class SymbolListModel extends AbstractListModel {
    private List<Symbol> data;
    private List<Symbol> filteredData;
    private String category;
    
    /** Creates a new instance of SymbolListModel
     */
    public SymbolListModel() {
        data = new ArrayList<Symbol>();
        filteredData = new ArrayList<Symbol>();
    }
    
    /** Set the category or null to show all
     * @param category category to shown, act as filter
     */
    public void setCategory(String category) {
        int index0 = 0;
        int index1 = filteredData.size()-1;
        if (index1 < 0) {
            index1 = 0;
        }
        
        filteredData.clear();
        this.category = category;
        if (category == null) {
            filteredData.addAll(data);
        } else {
            // applying filter
            for (int i=0; i<data.size(); i++) {
                Symbol symbol = data.get(i);
                if (category.equals(symbol.getCategory())) {
                    filteredData.add(symbol);
                }
            }
        }
        
        if (index1 < filteredData.size()-1) {
            index1 = filteredData.size()-1;
        }
        
        fireContentsChanged(this,index0,index1);
    }
    
    /** {@inheritDoc} */
    public Object getElementAt(int index) {
        return filteredData.get(index);
    }
    
    /** {@inheritDoc} */
    public int getSize() {
        return filteredData.size();
    }
    
    /** Add Symbol
     * @param symbol Symbol to be added
     */
    public void addElement(Symbol symbol) {
        data.add(symbol);
        setCategory(category);
    }
    
    /** Remove specified symbol
     * @param symbol Symbol to be removed
     * @return true if success otherwise false
     */
    public boolean removeElement(Symbol symbol) {
        int indexOf = data.indexOf(symbol);
        if (indexOf > -1) {
            data.remove(indexOf);
            setCategory(category);
            return true;
        }
        return false;
    }
}
