package org.jerrymouse.chineseCalendar.model.birthday;

import java.util.Calendar;
import java.util.Date;

import org.springframework.stereotype.Component;

@Component
public class PeriodUpdater {
	public static final long DAY_M = 1000 * 60 * 60 * 24;
	public static final long WEEK_M = DAY_M * 7;

	private Period thisMonth;
	private long thisMonthEndTime;

	private Period nextWeek;
	private long nextWeekEndTime;

	private Period lastWeek;
	private long lastWeekEndTime;

	private Period thisWeek;
	private long thisWeekEndTime;

	private Period thisYear;
	private long thisYearEndTime;

	public Period getNextWeek() {
		if (getTime() > nextWeekEndTime) {
			Calendar calendar = Calendar.getInstance();
			int weekNo = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			long time = calendar.getTime().getTime() - weekNo * DAY_M + WEEK_M;
			nextWeek = new Period(new SimpleCalendar(new Date(time)),
					new SimpleCalendar(new Date(time + WEEK_M)));
			nextWeekEndTime = nextWeek.end.getTime().getTime();
		}
		return nextWeek;
	}

	public Period getThisMonth() {
		if (getTime() > thisMonthEndTime) {
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			SimpleCalendar begin = new SimpleCalendar(calendar);
			calendar.add(Calendar.MONTH, 1);
			thisMonth = new Period(begin, new SimpleCalendar(calendar));
			thisMonthEndTime = thisMonth.end.getTime().getTime();
		}
		return thisMonth;
	}

	public Period getThisWeek() {
		if (getTime() > thisWeekEndTime) {
			Calendar calendar = Calendar.getInstance();
			int weekNo = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			long time = calendar.getTime().getTime() - weekNo * DAY_M;
			thisWeek = new Period(new SimpleCalendar(new Date(time)),
					new SimpleCalendar(new Date(time + WEEK_M)));
			thisWeekEndTime = thisWeek.end.getTime().getTime();
		}
		return thisWeek;
	}

	public Period getThisYear() {
		if (getTime() > thisYearEndTime) {
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.DAY_OF_YEAR, 1);
			SimpleCalendar begin = new SimpleCalendar(calendar);
			calendar.add(Calendar.YEAR, 1);
			thisYear = new Period(begin, new SimpleCalendar(calendar));
			thisYearEndTime = thisYear.end.getTime().getTime();
		}
		return thisYear;
	}

	private long getTime() {
		return new Date().getTime();
	}

	public Period getLastWeek() {
		if (getTime() > lastWeekEndTime) {
			Calendar calendar = Calendar.getInstance();
			int weekNo = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			long time = calendar.getTime().getTime() - weekNo * DAY_M;
			lastWeek = new Period(new SimpleCalendar(new Date(time - WEEK_M)),
					new SimpleCalendar(new Date(time)));
			lastWeekEndTime = lastWeek.end.getTime().getTime();
		}
		return lastWeek;
	}

}
