package com.brilliance.isc.common.irtcal.days.impl;

import com.brilliance.isc.common.irtcal.days.IrtDaysCalculator;
import com.brilliance.mda.runtime.mda.util.Dates;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("M30")
public class M30IrtDaysCalculatorImpl implements IrtDaysCalculator {

    @Override
    public int calculateDays(Date begdat, Date enddat, boolean includeEnddat) {
        int y1 = Dates.getYear(begdat);
        int m1 = Dates.getMonth(begdat);
        int d1 = Dates.getDay(begdat);
        int y2 = Dates.getYear(enddat);
        int m2 = Dates.getMonth(enddat);
        int d2 = Dates.getDay(enddat);
        int days = 0;
        if (y1 == y2 && m1 == m2) {
            // begin and end in same month
            days = d2 - d1;
            // if closed period, add 1 day but never return value > 30
            if (includeEnddat) {
                if (days < 30) {
                    days = days + 1;
                }
            }
        } else {
            // full month
            int month = (12 - m1) + (m2 - 1) + (y2 - y1 - 1) * 12;
            // days in 1st month
            int dayfirst = 30 - d1 + 1;
            if (dayfirst > 30) {
                dayfirst = 30;
            }
            // days in last month
            int daylast = d2 - 1;
            // if closed period, add 1 day in last month but never > 30
            if (includeEnddat) {
                if (daylast < 30) {
                    daylast = daylast + 1;
                }
            }
            days = month * 30 + dayfirst + daylast;
        }
        return days;
    }
}
