/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.unix.strftime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class StrftimeWareki {

	private static final SimpleDateFormat FMT =
		new SimpleDateFormat("yyyy/MM/dd");
	private static final Date EPOCH_HEISEI = fmt("1989/01/08");
	private static final Date EPOCH_SHOWA  = fmt("1926/12/25");
	private static final Date EPOCH_TAISHO = fmt("1912/07/30");
	private static final Date EPOCH_MEIJI  = fmt("1868/10/23");

	private static final Date[] EPOCHS = new Date[] {
		EPOCH_HEISEI, EPOCH_SHOWA, EPOCH_TAISHO, EPOCH_MEIJI, null
	};

	private static final String[] EPOCH_NAMES = new String[] {
		"平成", "昭和", "大正", "明治", "明治以前"
	};

	private static final String[] EPOCH_SHORT_NAMES = new String[] {
		"H", "S", "T", "M"
	};

	/**
	 * 
	 */
	public static StrftimeWareki LONG =
		new StrftimeWareki(EPOCH_NAMES);

	/**
	 * 
	 */
	public static StrftimeWareki SHORT =
		new StrftimeWareki(EPOCH_SHORT_NAMES);

	//
	private String[] names;

	//
	StrftimeWareki(String[] names) {
		this.names = names;
	}

	private static Date fmt(String s) {
		try {
			return FMT.parse(s);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	public String getEra(Date date) {
		for(int i = 0; i < EPOCHS.length; i++) {
			if(EPOCHS[i] == null || !date.before(EPOCHS[i])) {
				return i < names.length ? names[i] : "?";
			}
		}
		return "?";
	}

	public int getYear(Date date) {
		Calendar c, d;

		for(int i = 0; i < EPOCHS.length; i++) {
			if(EPOCHS[i] == null) {
				return 0;
			} else if(!date.before(EPOCHS[i])) {
				c = new GregorianCalendar();
				d = new GregorianCalendar();
				c.setTime(date);
				d.setTime(EPOCHS[i]);
				return c.get(Calendar.YEAR) - d.get(Calendar.YEAR) + 1;
			}
		}
		return 0;
	}

}
