package pt.utl.ist.scripts.process.updateData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import net.sourceforge.fenixedu.domain.CurricularCourse;
import net.sourceforge.fenixedu.domain.CurricularCourseScope;
import net.sourceforge.fenixedu.domain.ExecutionYear;
import pt.utl.ist.scripts.commons.AtomicScript;

public class UpdateCurricularCourseDates extends AtomicScript {

    @Override
    protected void run() throws Exception {

        List<CurricularCourse> curricularCourses = CurricularCourse.readCurricularCourses();
        System.out.println("li " + curricularCourses.size());

        List<ExecutionYear> executionYears = new ArrayList<ExecutionYear>(rootDomainObject.getExecutionYearsSet());
        Collections.sort(executionYears);

        for (CurricularCourse curricularCourse : curricularCourses) {
            for (CurricularCourseScope curricularCourseScope : curricularCourse.getScopes()) {
                updateDates(curricularCourseScope, executionYears);
            }
        }

    }

    private void updateDates(CurricularCourseScope curricularCourseScope, List<ExecutionYear> executionYears) throws Exception {
        ExecutionYear beginExecutionYear = getExecutionYearByDate(executionYears, curricularCourseScope.getBegin());
        if (beginExecutionYear == null) {
            throw new Exception("não enontrou Year para a data " + curricularCourseScope.getBegin());
        }
        curricularCourseScope.setBegin(beginExecutionYear.getBeginDate());

        if (curricularCourseScope.getEnd() != null) {
            ExecutionYear endExecutionYear = getExecutionYearByDate(executionYears, curricularCourseScope.getEnd());
            if (endExecutionYear == null) {
                throw new Exception("não enontrou Year para a data " + curricularCourseScope.getBegin());
            }
            curricularCourseScope.setEnd(endExecutionYear.getEndDate());
        }
    }

    private ExecutionYear getExecutionYearByDate(List<ExecutionYear> executionYears, Date date) {
        for (ExecutionYear year : executionYears) {
            if (year.getBeginDate().getTime() <= date.getTime() && year.getEndDate().getTime() >= date.getTime()) {
                return year;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        process(new UpdateCurricularCourseDates());
        System.exit(0);
    }
}
