package net.sourceforge.ganttproject.calendar;

import java.util.Date;

import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.gui.options.model.DefaultDateOption;
import net.sourceforge.ganttproject.gui.options.model.GPOption;
import net.sourceforge.ganttproject.gui.options.model.GPOptionGroup;

public class BusinessHoursOptions extends GPOptionGroup {
    public BusinessHoursOptions(IGanttProject project) {
        super("business-hours", createOptions(project));
    }

    private static GPOption[] createOptions(IGanttProject project) {
        LoadingSemaphor semaphor = new LoadingSemaphor(project.getActiveCalendar());
        return new GPOption[] {
            new BusinessHourOption("day-start", project.getActiveCalendar().getBusinessDayStart(), semaphor) {
                @Override
                public void loadPersistentValue(String value) {
                    super.loadPersistentValue(value);
                    mySemaphor.setStartDate(getValue());
                }
            },
            new BusinessHourOption("day-end", project.getActiveCalendar().getBusinessDayEnd(), semaphor) {
                @Override
                public void loadPersistentValue(String value) {
                    super.loadPersistentValue(value);
                    mySemaphor.setEndDate(getValue());
                }                
            }
        };
    }
    
    private static class LoadingSemaphor {
        private Date myEndDate;
        private Date myStartDate;
        private final GPCalendar myCalendar;
        LoadingSemaphor(GPCalendar calendar) {
            myCalendar = calendar;
        }
        void setStartDate(Date date){
            myStartDate = date;
            if (myEndDate != null) {
                myCalendar.setBusinessHours(myStartDate, myEndDate);
            }
        }
        void setEndDate(Date date) {
            myEndDate = date;
            if (myStartDate != null) {
                myCalendar.setBusinessHours(myStartDate, myEndDate);
            }
        }
    }
    private static class BusinessHourOption extends DefaultDateOption {
        protected final LoadingSemaphor mySemaphor;

        public BusinessHourOption(String id, Date initialValue, LoadingSemaphor semaphor) {
            super(id, initialValue);
            mySemaphor = semaphor;
        }
    };
}
