package net.sourceforge.ganttproject.gui.options.model;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import net.sourceforge.ganttproject.language.GanttLanguage;

public class DefaultDateOption extends GPAbstractOption implements DateOption {

    private Date myLockedValue;
    private Date myValue;
    
    public DefaultDateOption(String id) {
        this(id, new Date());
    }
    public DefaultDateOption(String id, Date initialValue) {
        super(id);
        myValue = initialValue;
    }

    public void setValue(Date value) {
        if (!isLocked()) {
            throw new IllegalStateException("Lock option before setting value");
        }
        setValue(value, false);
    }

    protected void setValue(Date value, boolean reset) {
        if (reset) {
            myValue = value;
        }
           fireChangeValueEvent(new ChangeValueEvent(getID(), myLockedValue, value));
        myLockedValue = value;    	
    }
    public Date getValue() {
        return myValue;
    }
    
    public DateFormat getDateFormat() {
        return null;
    }

    public DateFormat getTimeFormat() {
        return null;
    }
    @Override
    public void lock() {
        super.lock();
        myLockedValue = myValue;
    }
    public void commit() {
        super.commit();
        myValue = myLockedValue;
    }

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

    public String getPersistentValue() {
        if (getValue()==null) {
            return null;
        }
        DateFormat df = new SimpleDateFormat("HH:mmZ");
        if (df==null) {
            df = GanttLanguage.getInstance().getDateFormat();
        }
        df.setTimeZone(TimeZone.getDefault());
        return df.format(getValue());
    }

    public void loadPersistentValue(String value) {
        DateFormat df = new SimpleDateFormat("HH:mmZ");
        df.setTimeZone(TimeZone.getDefault());
        try {
            setValue(df.parse(value), true);
        } catch (ParseException e) {
            setValue(null);
        }
    }    

    protected Date getLockedValue() {
        return myLockedValue;
    }
}
