package org.jerrymouse.chineseCalendar.model.birthday;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

@Component
public class LunarCacluator {
	private int BEGIN_YEAR = 1955;
	private int END_YEAR = 2045;

	private Map<SimpleCalendar, SimpleCalendar> map;
	private Map<SimpleCalendar, SimpleCalendar> oppositeMap;

	public LunarCacluator() {
		map = build(BEGIN_YEAR - 5, END_YEAR + 5);
		oppositeMap = buildOpposite();
	}

	private Map<SimpleCalendar, SimpleCalendar> build(int beginYear, int endYear) {
		Map<SimpleCalendar, SimpleCalendar> map = new HashMap<SimpleCalendar, SimpleCalendar>();
		Calendar calendar = Calendar.getInstance();
		calendar.set(beginYear, 0, 1);
		while (calendar.get(Calendar.YEAR) < endYear) {
			SimpleCalendar yang = new SimpleCalendar(calendar);
			Lunar lunar = new Lunar(calendar);
			SimpleCalendar ying = new SimpleCalendar(lunar);
			map.put(yang, ying);
			calendar.add(Calendar.DATE, 1);
		}
		return map;
	}

	private Map<SimpleCalendar, SimpleCalendar> buildOpposite() {
		Map<SimpleCalendar, SimpleCalendar> oppositeMap = new HashMap<SimpleCalendar, SimpleCalendar>();
		for (Map.Entry<SimpleCalendar, SimpleCalendar> e : map.entrySet()) {
			oppositeMap.put(e.getValue(), e.getKey());
		}
		return oppositeMap;
	}

	public Map<SimpleCalendar, SimpleCalendar> getMap() {
		return map;
	}

	public Map<SimpleCalendar, SimpleCalendar> getOppositeMap() {
		return oppositeMap;
	}

	public SimpleCalendar toLunar(SimpleCalendar simpleCalendar) {
		SimpleCalendar temp = map.get(simpleCalendar);
		try {
			temp = (SimpleCalendar) temp.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return temp;
	}

	public SimpleCalendar toNormal(SimpleCalendar simpleCalendar) {
		SimpleCalendar temp = null;
		try {
			temp = (SimpleCalendar) oppositeMap.get(simpleCalendar).clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return temp;
	}
}
