package com.smppw.core.reta.calc;

import com.smppw.common.pojo.dto.DateValue;
import com.smppw.common.pojo.enums.Frequency;
import com.smppw.common.pojo.enums.Indicator;
import com.smppw.core.reta.IndicatorFactory;
import com.smppw.core.reta.Rate;
import com.smppw.utils.DateUtil;
import org.joda.time.DateTime;

import java.util.List;

/**
 * @author zhengsongliang
 * @datetime 2017年7月27日 上午10:04:32
 */
public class AnnualReturn extends Rate {
	@Override
	public Double calc(List<DateValue> dateValues) {
		return calc(dateValues, false);
	}

	public Double calc(List<DateValue> dateValues, boolean followGIPSRule) {
		Rate rate = IndicatorFactory.getInstance().get(Indicator.IntervalReturn);
		Double intervalReturn = rate.calc(dateValues);
		if (dateValues == null) {
			return null;
		}

		int n = dateValues.size();
		if (intervalReturn == null || n < 2)
			return null;

		String firstDate = dateValues.get(0).getDate();
		String lastDate = dateValues.get(n - 1).getDate();

		// 小于一年不年化
		if (followGIPSRule) {
			boolean lessThanOneYear = lessThanOneYear(firstDate, lastDate);
			if (lessThanOneYear)
				return intervalReturn;
		}

		Double annualReturn = intervalReturn;
		int dateDis = DateUtil.getDateDistance(firstDate, lastDate, Frequency.Daily, false);

		if (dateDis == 8) {
			annualReturn = Math.pow(1 + intervalReturn, Frequency.Weekly.getNum()) - 1;
		} else {
			annualReturn = Math.pow(1 + intervalReturn, 365.25 / dateDis) - 1;
		}

		return annualReturn;
	}
	
	// GIPS少于一年不年化
	private boolean lessThanOneYear(String startDate, String endDate) {
		DateTime startDT = DateTime.parse(startDate).withMillisOfDay(0);
		DateTime endDT = DateTime.parse(endDate).withMillisOfDay(0);

		DateTime oneYearAgo = endDT.minusYears(1).plusDays(1);
		return oneYearAgo.isBefore(startDT);
	}
}
