package org.systemsbiology.infocore.namegrabber;


import java.util.List;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.MutableComboBoxModel;


/**
 * holds data for drop-down menus of source and target naming systems.
 */
public class SynonymDbComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
    Vector<Object> objects = new Vector<Object>();
    Object selectedObject;

    public SynonymDbComboBoxModel() {}

    public SynonymDbComboBoxModel(Object[] items) {
        addAll(items);
    }

    public void addAll(List<? extends Object> list) {
        for (Object obj : list) {
            objects.add(obj);
        }
        fireContentsChanged(this, -1, -1);
    }

    public void addAll(Object[] list) {
        for (Object obj : list) {
            objects.add(obj);
        }
        fireContentsChanged(this, -1, -1);
    }

    public void selectFirst() {
        if (objects.size() > 0) {
            setSelectedItem(objects.get(0));
        }
    }

    public void clear() {
        objects.clear();
        fireContentsChanged(this, -1, -1);
    }

    public synchronized void addElement(Object obj) {
        objects.add(obj);
        fireIntervalAdded(this,objects.size()-1, objects.size()-1);
        if ( objects.size() == 1 && selectedObject == null && obj != null ) {
            setSelectedItem(obj);
        }
    }

    public synchronized void insertElementAt(Object obj, int index) {
        objects.add(index, obj);
        fireIntervalAdded(this, index, index);
    }

    public synchronized void removeElement(Object obj) {
        int index = objects.indexOf(obj);
        removeElementAt(index);
    }

    public synchronized void removeElementAt(int index) {
        if (index >= 0 && index < objects.size()) {
            objects.remove(index);
            fireIntervalRemoved(this, index, index);
        }
    }

    public synchronized Object getElementAt(int index) {
        if ( index >= 0 && index < objects.size() )
            return objects.elementAt(index);
        else
            return null;
    }

    public synchronized int getSize() {
        return objects.size();
    }

    public synchronized Object getSelectedItem() {
        return selectedObject;
    }

    public synchronized void setSelectedItem(Object anObject) {
        if ((selectedObject != null && !selectedObject.equals(anObject)) || selectedObject == null && anObject != null) {
            selectedObject = anObject;
            fireContentsChanged(this, -1, -1);
        }
    }
}
