package com.magistr.app.utils;

import com.magistr.app.model.SemesterType;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;

@Service
public class CourseAndSemesterCalculator {

    public static int getActualCourse(Integer yearStartStudy) {
        return getActualCourse(yearStartStudy, LocalDate.now(ZoneId.of("Europe/Moscow")));
    }

    public static int getActualCourse(Integer yearStartStudy, LocalDate date) {
        int currentYear = date.getYear();
        int currentMonth = date.getMonthValue();
        int course = currentMonth >= 9
                ? currentYear - yearStartStudy + 1
                : currentYear - yearStartStudy;
        return Math.max(0, course);
    }

    public static int getActualSemester(Integer yearStartStudy) {
        return getActualSemester(yearStartStudy, LocalDate.now(ZoneId.of("Europe/Moscow")));
    }

    public static int getActualSemester(Integer yearStartStudy, LocalDate date) {
        int course = getActualCourse(yearStartStudy, date);
        if (course == 0) {
            return 0;
        }
        int currentMonth = date.getMonthValue();

        if (currentMonth <= 1 || currentMonth >= 9) {
            return course * 2 - 1;
        } else {
            return course * 2;
        }
    }

    public static int getFutureCourse(Integer yearStartStudy, String periodYears) {
        int recordYear = Integer.parseInt(periodYears.substring(0, 4));
        return Math.max(0, recordYear - yearStartStudy + 1);
    }

    public static int getFutureSemester(Integer yearStartStudy, String periodYears, SemesterType semesterType) {
        int course = getFutureCourse(yearStartStudy, periodYears);
        if (course == 0) {
            return 0;
        }

        if (semesterType == SemesterType.autumn) {
            return course * 2 - 1;
        } else if (semesterType == SemesterType.spring) {
            return course * 2;
        }
        throw new IllegalArgumentException("Неизвестный semesterType: " + semesterType);
    }
}
