package pt.utl.ist.scripts.runOnce.accounting;

import java.io.Serializable;
import java.util.Locale;

import net.sourceforge.fenixedu.domain.phd.PhdIndividualProgramProcess;
import net.sourceforge.fenixedu.domain.phd.PhdIndividualProgramProcessState;
import net.sourceforge.fenixedu.domain.phd.PhdProgram;
import net.sourceforge.fenixedu.domain.phd.debts.PhdGratuityEvent;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.LocalDate;

import pt.ist.bennu.core.domain.Bennu;
import pt.utl.ist.fenix.tools.util.i18n.Language;
import pt.utl.ist.scripts.Cron.CronScript;

public class CreatePhdGratuityEvents extends CronScript {

    private int GratuityEvent_TOTAL_CREATED = 0;

    @Override
    protected Serializable runProcess() throws Exception {
        Language.setLocale(new Locale("PT", "pt"));
        generateGratuityEventsForAllStudents();
        logger.warn(String.format("Created %d GratuityEvent events", GratuityEvent_TOTAL_CREATED));

        return null;
    }

    private void generateGratuityEventsForAllStudents() {
        for (PhdProgram program : Bennu.getInstance().getPhdProgramsSet()) {
            Outer: for (PhdIndividualProgramProcess process : program.getIndividualProgramProcesses()) {
                if (process.getActiveState().equals(PhdIndividualProgramProcessState.WORK_DEVELOPMENT)) {
                    int year = new LocalDate().getYear();
                    if (process.hasPhdGratuityEventForYear(year)) {
                        continue;
                    }
                    LocalDate whenFormalizedRegistration = process.getWhenFormalizedRegistration();
                    LocalDate currentYearAniversary =
                            new LocalDate(year, whenFormalizedRegistration.getMonthOfYear(),
                                    whenFormalizedRegistration.getDayOfMonth());
                    for (PhdGratuityEvent event : process.getPhdGratuityEvents()) {
                        if (event.isCancelled()) {
                            continue;
                        }
                        Interval period = new Interval(currentYearAniversary.toDateMidnight(), new LocalDate().toDateMidnight());
                        if (period.contains(event.getWhenOccured())) {
                            continue Outer;
                        }
                    }

                    GratuityEvent_TOTAL_CREATED++;
                    generateGratuity(process);
                }
            }
        }
    }

    private void generateGratuity(final PhdIndividualProgramProcess process) {
        PhdGratuityEvent
                .create(process, new DateTime().getYear(), process.getWhenFormalizedRegistration().toDateTimeAtMidnight());
    }
}
