/**
   * Checks if person belongs to curricular course. The unit path format should be:
   * IST{.<SubUnitAcronym>}.<DegreeAcronym>.<CurricularCourseAcronym>
   *
   * <p>Accepted roles: STUDENT
   *
   * @param person
   * @param groupCheckQuery
   * @return
   * @throws NonExistingServiceException
   * @throws ExcepcaoPersistencia
   */
  private static Boolean checkCurricularCourseGroup(Person person, GroupCheckQuery groupCheckQuery)
      throws NonExistingServiceException {
    final String[] unitAcronyms = groupCheckQuery.unitFullPath.split("\\.");

    if (!groupCheckQuery.roleType.equals("STUDENT")) {
      throw new NonExistingServiceException();
    }

    for (final DegreeCurricularPlan degreeCurricularPlan :
        getDegree(unitAcronyms).getActiveDegreeCurricularPlans()) {

      final CurricularCourse curricularCourse =
          degreeCurricularPlan.getCurricularCourseByAcronym(unitAcronyms[4]);

      if (curricularCourse != null) {
        List<Enrolment> enrolments =
            curricularCourse.getEnrolmentsByExecutionPeriod(
                getExecutionPeriod(groupCheckQuery.year, groupCheckQuery.semester));
        for (Enrolment enrolment : enrolments) {
          if (enrolment.getStudentCurricularPlan().getRegistration().getPerson().equals(person)) {
            return true;
          }
        }
      }
    }

    return false;
  }
 @Override
 public boolean isMember(User user) {
   if (user == null) {
     return false;
   }
   if (user.getPerson().getStudent() != null) {
     final Set<CompetenceCourse> competenceCourses = executionCourse.getCompetenceCourses();
     for (Registration registration : user.getPerson().getStudent().getRegistrationsSet()) {
       // students of any degree sharing the same competence of the given execution course
       for (StudentCurricularPlan studentCurricularPlan :
           registration.getStudentCurricularPlansSet()) {
         for (Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) {
           CompetenceCourse competenceCourse =
               enrolment.getCurricularCourse().getCompetenceCourse();
           if (competenceCourses.contains(competenceCourse)) {
             return true;
           }
         }
       }
       // students attending the given execution course (most will be in the previous case but some
       // may not)
       if (registration.getAttendingExecutionCoursesFor().contains(executionCourse)) {
         return true;
       }
     }
   }
   return false;
 }
  private void createTreeCurriculumModules(
      StudentCurricularPlan studentCurricularPlan,
      ExecutionSemester executionSemester,
      java.util.List<java.util.List<MarkSheetEnrolmentEvaluationBean>> enrolmentEvaluationBeanList,
      java.util.List<java.util.List<MarkSheetEnrolmentEvaluationBean>>
          finalEnrolmentEvaluationBeanList,
      java.util.List<Enrolment> enrolments,
      boolean forEdition) {
    RootCurriculumGroup module = studentCurricularPlan.getRoot();
    enrolments =
        enrolments != null
            ? enrolments
            : new java.util.ArrayList<Enrolment>(module.getEnrolmentsBy(executionSemester));

    for (Enrolment enrolment : enrolments) {
      java.util.List<MarkSheetEnrolmentEvaluationBean> markSheetList =
          new java.util.ArrayList<MarkSheetEnrolmentEvaluationBean>();
      for (EvaluationSeason season :
          EvaluationConfiguration.getInstance().getEvaluationSeasonSet()) {
        markSheetList.add(
            new MarkSheetEnrolmentEvaluationBean(enrolment, executionSemester, season));
      }

      if (enrolment.hasAnyNonTemporaryEvaluations() && !forEdition) {
        finalEnrolmentEvaluationBeanList.add(markSheetList);
      } else {
        enrolmentEvaluationBeanList.add(markSheetList);
      }
    }
  }
  public ActionForward unEnrol(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    Enrolment enrolment = readEnrolment(request);

    try {
      final RuleResult ruleResults =
          EnrolBolonhaStudent.run(
              readStudentCurricularPlan(request),
              enrolment.getExecutionPeriod(),
              new ArrayList<IDegreeModuleToEvaluate>(),
              Arrays.asList(new CurriculumModule[] {enrolment}),
              CurricularRuleLevel.ENROLMENT_NO_RULES);

      if (ruleResults.isWarning()) {
        addRuleResultMessagesToActionMessages("warning", request, ruleResults);
      }

    } catch (EnrollmentDomainException ex) {
      addRuleResultMessagesToActionMessages("error", request, ex.getFalseResult());
    } catch (DomainException ex) {
      addActionMessage("error", request, ex.getKey(), ex.getArgs());
    }

    return prepareSetEvaluations(mapping, actionForm, request, response);
  }
  public ActionForward prepareEditEvaluation(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    Enrolment enrolment = getEnrolmentForEdition(request);
    ExecutionSemester executionSemester = readExecutionSemester(request);
    StudentCurricularPlan studentCurricularPlan = readStudentCurricularPlan(request);

    java.util.List<Enrolment> enrolmentToUse = new java.util.ArrayList<Enrolment>();
    enrolmentToUse.add(enrolment);

    java.util.List<java.util.List<MarkSheetEnrolmentEvaluationBean>> enrolmentEvaluationBeanList =
        new java.util.ArrayList<java.util.List<MarkSheetEnrolmentEvaluationBean>>();
    createTreeCurriculumModules(
        studentCurricularPlan,
        executionSemester,
        enrolmentEvaluationBeanList,
        null,
        enrolmentToUse,
        true);

    request.setAttribute("entriesList", enrolmentEvaluationBeanList);

    request.setAttribute("allEvaluationsBound", enrolment.getEvaluationsSet());

    return mapping.findForward("show-edit-evaluation-form");
  }
  /**
   * Checks if person belongs to deparment on a specified execution year. The unit path format
   * should be: IST.<DepartmentAcronym>
   *
   * <p>Accepted roles: STUDENT, TEACHER and EMPLOYEE
   *
   * @param person
   * @param groupCheckQuery
   * @return
   * @throws ExcepcaoPersistencia
   * @throws FenixServiceException
   */
  private static Boolean checkDepartmentGroup(Person person, GroupCheckQuery groupCheckQuery)
      throws NonExistingServiceException {

    final String[] unitAcronyms = groupCheckQuery.unitFullPath.split("\\.");
    if (!groupCheckQuery.roleType.equals("TEACHER")
        && !groupCheckQuery.roleType.equals("STUDENT")
        && !groupCheckQuery.roleType.equals("EMPLOYEE")) {
      throw new NonExistingServiceException();
    }

    if (groupCheckQuery.roleType.equals("TEACHER")) {
      return TeacherGroup.get(getDepartment(unitAcronyms), getExecutionYear(groupCheckQuery.year))
          .isMember(person.getUser());
    } else if (groupCheckQuery.roleType.equals("EMPLOYEE")) {
      if (person != null && person.getEmployee() != null) {
        final Department lastDepartmentWorkingPlace =
            person
                .getEmployee()
                .getLastDepartmentWorkingPlace(
                    getExecutionYear(groupCheckQuery.year).getBeginDateYearMonthDay(),
                    getExecutionYear(groupCheckQuery.year).getEndDateYearMonthDay());
        return (lastDepartmentWorkingPlace != null
            && lastDepartmentWorkingPlace.equals(getDepartment(unitAcronyms)));
      }
      return false;
    } else {
      if (person != null && person.getStudent() != null) {
        for (final Registration registration : person.getStudent().getRegistrationsSet()) {
          for (final Enrolment enrolment :
              registration
                  .getLastStudentCurricularPlan()
                  .getEnrolmentsByExecutionYear(getExecutionYear(groupCheckQuery.year))) {
            if (enrolment.getCurricularCourse().getCompetenceCourse() != null) {
              final CompetenceCourse competenceCourse =
                  enrolment.getCurricularCourse().getCompetenceCourse();
              if (competenceCourse.getDepartmentsSet().contains(getDepartment(unitAcronyms))) {
                return true;
              }

              if (competenceCourse.hasDepartmentUnit()
                  && competenceCourse.getDepartmentUnit().getDepartment()
                      == getDepartment(unitAcronyms)) {
                return true;
              }
            }
          }
        }
      }
      return false;
    }
  }
  @Atomic
  public static void run(final String studentCurricularPlanId)
      throws DomainException, NonExistingServiceException {
    final StudentCurricularPlan studentCurricularPlan =
        FenixFramework.getDomainObject(studentCurricularPlanId);

    if (studentCurricularPlan != null) {

      for (Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) {
        for (EnrolmentEvaluation evaluation : enrolment.getEvaluationsSet()) {
          evaluation.setEnrolmentEvaluationState(EnrolmentEvaluationState.TEMPORARY_OBJ);
        }
      }

      studentCurricularPlan.delete();
    } else {
      throw new NonExistingServiceException();
    }
  }
  protected void putAllStudentsStatisticsInTheRequest(
      HttpServletRequest request,
      List<StudentCurricularPlan> students,
      ExecutionYear currentMonitoringYear) {
    Map<Integer, TutorStatisticsBean> statisticsByApprovedEnrolmentsNumber =
        new HashMap<Integer, TutorStatisticsBean>();

    int maxApprovedEnrolments = 0;

    for (StudentCurricularPlan scp : students) {
      List<Enrolment> enrolments = scp.getEnrolmentsByExecutionYear(currentMonitoringYear);
      int approvedEnrolments = 0;

      for (Enrolment enrolment : enrolments) {
        if (!enrolment.getCurricularCourse().isAnual()
            && enrolment.getEnrollmentState().equals(EnrollmentState.APROVED)) {
          approvedEnrolments++;
        }
      }

      maxApprovedEnrolments = Math.max(maxApprovedEnrolments, approvedEnrolments);

      if (statisticsByApprovedEnrolmentsNumber.containsKey(approvedEnrolments)) {
        TutorStatisticsBean tutorStatisticsbean =
            statisticsByApprovedEnrolmentsNumber.get(approvedEnrolments);
        tutorStatisticsbean.setStudentsNumber(tutorStatisticsbean.getStudentsNumber() + 1);
      } else {
        TutorStatisticsBean tutorStatisticsBean =
            new TutorStatisticsBean(1, approvedEnrolments, students.size());
        tutorStatisticsBean.setApprovedEnrolmentsNumber(approvedEnrolments);
        statisticsByApprovedEnrolmentsNumber.put(approvedEnrolments, tutorStatisticsBean);
      }
    }

    putStatisticsInTheRequest(
        request,
        maxApprovedEnrolments,
        students.size(),
        statisticsByApprovedEnrolmentsNumber,
        "allStudentsStatistics");
  }
 private void load(final CurriculumModule curriculumModule) {
   if (curriculumModule != null) {
     curriculumModule.getCreationDateDateTime();
     final DegreeModule degreeModule = curriculumModule.getDegreeModule();
     if (degreeModule != null) {
       degreeModule.getName();
     }
     if (curriculumModule.isCurriculumLine()) {
       final CurriculumLine curriculumLine = (CurriculumLine) curriculumModule;
       if (curriculumLine.isEnrolment()) {
         final Enrolment enrolment = (Enrolment) curriculumLine;
         for (final EnrolmentEvaluation enrolmentEvaluation : enrolment.getEvaluationsSet()) {
           enrolmentEvaluation.getGrade();
         }
       }
     } else {
       final CurriculumGroup curriculumGroup = (CurriculumGroup) curriculumModule;
       for (final CurriculumModule child : curriculumGroup.getCurriculumModulesSet()) {
         load(child);
       }
     }
   }
 }
  public void initPerformance() {
    double totalEcts = 0;
    double approvedEcts = 0;

    Collection<Enrolment> enrolments = getTutorship().getStudent().getEnrolments(executionSemester);

    if (enrolments.isEmpty()) {
      highPerformance = false;
      lowPerformance = false;
      withoutEnrolments = true;
      return;
    }

    for (Enrolment enrolment : enrolments) {
      totalEcts += enrolment.getEctsCredits();

      if (enrolment.isApproved()) {
        approvedEcts += enrolment.getEctsCredits();
      }
    }

    this.highPerformance = (approvedEcts >= totalEcts);
    this.lowPerformance = (approvedEcts < (totalEcts / 2));
  }
  public ActionForward warmUpCacheForEnrolmentPeriodStart(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    final ExecutionSemester ces = ExecutionSemester.readActualExecutionSemester();
    final ExecutionSemester pes = ces == null ? null : ces.getPreviousExecutionPeriod();

    if (ces != null && pes != null) {
      long s = System.currentTimeMillis();
      for (final ExecutionCourse executionCourse : ces.getAssociatedExecutionCoursesSet()) {
        executionCourse.getName();
        for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) {
          courseLoad.getType();
          for (final Shift shift : courseLoad.getShiftsSet()) {
            shift.getNome();
            for (final SchoolClass schoolClass : shift.getAssociatedClassesSet()) {
              schoolClass.getNome();
              final ExecutionDegree executionDegree = schoolClass.getExecutionDegree();
              final DegreeCurricularPlan degreeCurricularPlan =
                  executionDegree.getDegreeCurricularPlan();
              degreeCurricularPlan.getName();
              final Degree degree = degreeCurricularPlan.getDegree();
              degree.getDegreeType();
              final RootCourseGroup root = degreeCurricularPlan.getRoot();
              load(root);
            }
            for (final Lesson lesson : shift.getAssociatedLessonsSet()) {
              lesson.getBeginHourMinuteSecond();
              for (OccupationPeriod period = lesson.getPeriod();
                  period != null;
                  period = period.getNextPeriod()) {
                period.getStartDate();
              }
              for (final LessonInstance lessonInstance : lesson.getLessonInstancesSet()) {
                lessonInstance.getBeginDateTime();
              }
            }
          }
        }
      }
      long e = System.currentTimeMillis();
      logger.info(
          "Warming up cache for enrolment period. Load of current semester information took {}ms.",
          e - s);

      s = System.currentTimeMillis();
      //            for (final RoomClassification roomClassification :
      // rootDomainObject.getRoomClassificationSet()) {
      //                for (final RoomInformation roomInformation :
      // roomClassification.getRoomInformationsSet()) {
      //                    roomInformation.getDescription();
      //                    final Room room = roomInformation.getRoom();
      //                    room.getNormalCapacity();
      //                }
      //            }
      e = System.currentTimeMillis();
      logger.info("Warming up cache for enrolment period. Load of room listing took {}ms.", e - s);

      final Set<Student> students = new HashSet<Student>();
      s = System.currentTimeMillis();
      for (final Enrolment enrolment : pes.getEnrolmentsSet()) {
        students.add(enrolment.getStudent());
      }
      e = System.currentTimeMillis();
      logger.info("Warming up cache for enrolment period. Search for students took {}ms.", e - s);

      s = System.currentTimeMillis();
      for (final Student student : students) {
        student.getNumber();
        for (final Registration registration : student.getRegistrationsSet()) {
          registration.getNumber();
          for (final StudentCurricularPlan studentCurricularPlan :
              registration.getStudentCurricularPlansSet()) {
            final RootCurriculumGroup root = studentCurricularPlan.getRoot();
            load(root);
          }
        }
      }
      e = System.currentTimeMillis();
      logger.info(
          "Warming up cache for enrolment period. Load of student curriculum took {}ms.", e - s);
    }

    return monitor(mapping, form, request, response);
  }