package com.kurukurupapa.tryandroid.fw.util;

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

public class DateUtil {
	public static String textOfShortHour = "h";
	public static String textOfShortMinute = "m";
	public static String textOfHour = "時間";
	public static String textOfMinute = "分";
	public static String textOfSecond = "秒";

	public static final long MILLIS_PER_SECOND = 1000;
	public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
	public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
	public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
	public static final long MILLIS_PER_YEAR = 365 * MILLIS_PER_DAY;

	static DateFormat dateTimeFormat = new SimpleDateFormat(
			"yyyy/MM/dd HH:mm:ss");

	private static int[] splitDurationTime(long milliSecond) {
		int sign = 1;
		if (milliSecond < 0) {
			milliSecond = -milliSecond;
			sign = -1;
		}

		int hour = (int) (milliSecond / MILLIS_PER_HOUR);
		milliSecond = milliSecond - hour * MILLIS_PER_HOUR;

		int minute = (int) (milliSecond / MILLIS_PER_MINUTE);
		milliSecond = milliSecond - minute * MILLIS_PER_MINUTE;

		int second = (int) (milliSecond / MILLIS_PER_SECOND);
		milliSecond = milliSecond - second * MILLIS_PER_SECOND;

		return new int[] { sign * hour, minute, second, (int) milliSecond };
	}

	public static String formatDurationTime(long milliSecond) {
		StringBuilder sb = new StringBuilder();
		int[] arr = splitDurationTime(milliSecond);
		if (arr[0] != 0) {
			sb.append(arr[0] + textOfHour);
		}
		if (arr[1] != 0 || sb.length() != 0) {
			sb.append(arr[1] + textOfMinute);
		}
		sb.append(arr[2] + textOfSecond);
		return sb.toString();
	}

	public static String formatShortDurationTime(long milliSecond) {
		StringBuilder sb = new StringBuilder();
		int[] arr = splitDurationTime(milliSecond);
		if (arr[0] != 0) {
			sb.append(arr[0] + textOfShortHour);
		}
		sb.append(arr[1] + textOfShortMinute);
		return sb.toString();
	}

	public static Date parseDateTime(String date) throws ParseException {
		return dateTimeFormat.parse(date);
	}

	public static String formatDateTime(Calendar calendar) {
		return formatDateTime(calendar.getTime());
	}

	public static String formatDateTime(Date date) {
		return dateTimeFormat.format(date);
	}

	public static String formatDateTime(long milliSecond) {
		return formatDateTime(new Date(milliSecond));
	}

}
