package com.capgemini.reports.common.scheduling.view;

import com.capgemini.reports.database.javabean.enumeration.SchedulingEnum;
import com.capgemini.reports.periodicity.*;

/** This class can interrogate the DB and show sub-period parameters either loaded with DB data, or empty. */
public class SchedulingParametersReader extends SchedulingFormatter {

    private static final WeeklyPeriod DEFAUT_VALUE_OF_WEEKLY = PeriodFactory.weekly(1);
    private static final DayInMonth DEFAUT_VALUE_OF_WEEKEND = PeriodFactory.dayInMonth(1);
    private static final DailyPeriod DEFAULT_VALUE_OF_DAILY = PeriodFactory.daily();

    /**
     * Return html code representing all the sub period data, pre-fileld or not.
     * 
     * @param currentlySelectedSubPeriod the requested sup-period to display. (weekly / weekend...)
     * @param existingUpdatePeriodFromDB optional, is present if isUpdate is true.
     * @param isUpdate a boolean, true if a report scheduling is being update
     * @return content sub period
     */
    public String getSubPeriod(final SchedulingEnum currentlySelectedSubPeriod, final SchedulingPeriod existingUpdatePeriodFromDB,
            final boolean isUpdate) {
        if (isUpdate && existingUpdatePeriodFromDB.getPeriodicity() == currentlySelectedSubPeriod) {
            return existingUpdatePeriodFromDB.accept(this).write();
        } else {
            return getSubPeriodForNewScheduling(currentlySelectedSubPeriod);
        }
    }

    /**
     * Return content of sub period.
     * 
     * @param subPeriod
     * @return content sub period
     */
    private String getSubPeriodForNewScheduling(final SchedulingEnum subPeriod) {
        final String result;
        switch (subPeriod) {
            case DAILY:
                result = this.visit(DEFAULT_VALUE_OF_DAILY).write();
                break;
            case WEEKLY:
                result = this.visit(DEFAUT_VALUE_OF_WEEKLY).write();
                break;
            case WEEKEND:
                result = this.visit(DEFAUT_VALUE_OF_WEEKEND).write();
                break;
            case DATE:
                result = this.visit(PeriodFactory.today()).write();
                break;
            default:
                throw new UnsupportedOperationException("Unable to understand scheduling sub-period of type " + subPeriod);
        }
        return result;
    }
}
