/*
 * MosP - Mind Open Source Project         http://www.mosp.jp/
 * Copyright (C) 1987-2009 MIND Co., Ltd.  http://www.e-mind.co.jp/
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package jp.mosp.payroll.base;

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

import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.common.MospUtility;

/**
 * MosP給与計算を開発する上で有用なメソッドを提供する。<br><br>
 */
public class PayrollUtility {
	
	/**
	 * 日付を取得する。
	 * @param strDate 日付(yyyymmdd)
	 * @return 日付
	 * @throws MospException 
	 */
	public static Date getDate(String strDate) throws MospException {
		if (strDate == null || strDate.length() != 8) {
			throw new MospException(MospConst.EX_DATE_INVALID);
		}
		return MospUtility.getDate(
				strDate.substring(0, 4) + PayrollConst.SEPARATOR_DATE +
				strDate.substring(4, 6) + PayrollConst.SEPARATOR_DATE +
				strDate.substring(6, 8));
	}
	
	/**
	 * 年齢を取得する。
	 * @param birthDate 生年月日
	 * @param toDate    年齢起算日
	 * @return 年齢
	 */
	public static int getAge(Date birthDate, Date toDate) {
		// 取得準備
		int age = 0;
		// 年齢取得
		age = MospUtility.getYear(toDate) - MospUtility.getYear(birthDate);
		// 年齢起算日が誕生年よりなら0
		if (age < 0) {
			age = 0;
			return age;
		}
		// 対象月が誕生月以降
		if (MospUtility.getMonth(toDate) - MospUtility.getMonth(birthDate) > 0) {
			return age;
		} else if (MospUtility.getMonth(toDate) - MospUtility.getMonth(birthDate) == 0) {
			// 対象日が誕生日以降
			if (MospUtility.getDay(toDate) - MospUtility.getDay(birthDate) > 0) {
				return age;
			} else if (MospUtility.getDay(toDate) - MospUtility.getDay(birthDate) == 0) {
				// 対象日が誕生日
				return age;
			} else {
				// 対象日が誕生日以前
				return age - 1;
			}
		} else {
			// 対象月が誕生月以前
			return age - 1;
		}
	}
	
	/**
	 * 日を操作する。
	 * @param date   操作日付
	 * @param amount 増減日数
	 * @return 操作後日付
	 */
	public static Date addDay(Date date, int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		cal.add(Calendar.DAY_OF_MONTH, amount);
		return cal.getTime();
	}
	
}
