/*
 * Created on 18.06.2005
 */
package net.sourceforge.ganttproject.gui.options.model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class DefaultEnumerationOption extends GPAbstractOption implements
        EnumerationOption, ChangeValueDispatcher {


    private final String[] myValues;

    private String myValue;

    private String myLockedValue;

    public DefaultEnumerationOption(String id, String[] values) {
        super(id);
        myValues = values; 
    }

    public DefaultEnumerationOption(String id, List<String> values) {
        super(id);
        myValues = values.toArray(new String[0]);
    }
    
    public DefaultEnumerationOption(String id, Object[] values) {
    	super(id);
    	List<String> buf = new ArrayList<String>();
    	for (Object nextValue : values) {
    		buf.add(objectToString(nextValue));
    	}
    	myValues = buf.toArray(new String[0]);
    }

    protected String objectToString(Object nextValue) {
    	assert nextValue!=null;
		return nextValue.toString();
	}

	public String[] getAvailableValues() {
        return myValues;
    }

    public void setValue(String value) {
        setValue(value, !isLocked());
    }

    protected void setValue(String value, boolean reset) {
        if (reset) {
            myValue = value;
        }
        ChangeValueEvent event = null;
        if (value!=null && myLockedValue!=null) {
        	if (!value.equals(myLockedValue)) {
        		event = new ChangeValueEvent(getID(), myLockedValue, value);
        	}
        }
        else if (false==(value==null && myLockedValue==null)) {
        	event = new ChangeValueEvent(getID(), myLockedValue, value);
        }
        myLockedValue = value;    	
        if (event!=null) {
        	fireChangeValueEvent(event);
        }
    }
    
    public String getValue() {
        return isLocked() ? myLockedValue : myValue;
    }

    public void commit() {
        super.commit();
        myValue = myLockedValue;
    }


    public String getPersistentValue() {
        return getValue();
    }

    public void loadPersistentValue(String value) {
        setValue(value);
    }    

    public boolean isChanged() {
        if (isLocked()) {
            if (myValue!=null) {
                return false==myValue.equals(myLockedValue);
            }
            else {
            	return myLockedValue!=null;
            }
        }
        return false;
    }
    
    protected String getLockedValue() {
        return myLockedValue;
    }

}
