package com.smppw.common.rollrange.date;

import com.smppw.constants.Consts;
import com.smppw.common.pojo.dto.DateRange;
import com.smppw.common.pojo.enums.Frequency;
import com.smppw.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.util.List;

/**
 * @author Yu Liu
 *
 */
public class DateVerifier {
	private static DateConvertorImpl convertor = new DateConvertorImpl();

	public static String verifyPeriodEnd(String endDate, Frequency freq) {
		if (null == endDate) {
			return endDate;
		}

		String periodEnd = convertor.setPeriodLast(endDate, freq, true);
		if (periodEnd.equals(endDate)) {
			return periodEnd;
		}

		String lastPeriodEnd = convertor.addPeriod(endDate, -1, freq, PeriodPosition.PeriodLast, false);
		return lastPeriodEnd;
	}
	
	public static String verifyPeriodStart(String startDate, Frequency freq) {
		if (null == startDate) {
			return startDate;
		}

		String periodStart = convertor.setPeriodFirst(startDate, freq);
		if (periodStart.equals(startDate)) {
			return periodStart;
		}

		String nextPeriodFirst = convertor.addPeriod(startDate, 1, freq, PeriodPosition.PeriodFirst, false);
		return nextPeriodFirst;
	}
	
	public static void verifyDateRanges(List<DateRange> drs, Frequency freq) {
		for (DateRange dr : drs) {
			dr.setStartDate(verifyPeriodStart(dr.getStartDate(), freq));
			dr.setEndDate(verifyPeriodEnd(dr.getEndDate(), freq));
		}
	}

	public static boolean verifyPeriodLegality(String startDate, String endDate) {
		if (convertor.convertToIndex(startDate) - convertor.convertToIndex(endDate) >= 0)
			return false;
		return true;
	}

	public static String getRankDate(String date) {
		if (StringUtils.isEmpty(date)) {
			return null;
		}
		if (DateUtil.getDatePattern(date) == Consts.SHORT_DATE_PATTERN) {
			return date;
		} else {
			return DateTime.parse(DateVerifier.verifyPeriodEnd(date, Frequency.Monthly))
					.toString(Consts.SHORT_DATE_PATTERN);
		}

	}
}
