package eu.dnetlib.is.util;

import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateUtils {

	private static final long SECOND = 1000;
	private static final long MINUTE = SECOND * 60;
	private static final long HOUR = MINUTE * 60;
	private static final long DAY = HOUR * 24;
	private static final long YEAR = DAY * 365;
	private static final SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);

	public static String elapsedTime(long t) {
		final StringWriter a = new StringWriter();

		boolean prependBlank = false;
		if (t >= YEAR) {
			a.append(floor(t, YEAR));
			a.append(' ');
			a.append('y');
			prependBlank = true;
		}
		t %= YEAR;
		if (t >= DAY) {
			if (prependBlank) {
				a.append(' ');
			}
			a.append(floor(t, DAY));
			a.append(' ');
			a.append('d');
			prependBlank = true;
		}
		t %= DAY;
		if (t >= HOUR) {
			if (prependBlank) {
				a.append(' ');
			}
			a.append(floor(t, HOUR));
			a.append(' ');
			a.append('h');
			prependBlank = true;
		}
		t %= HOUR;
		if (t >= MINUTE) {
			if (prependBlank) {
				a.append(' ');
			}
			a.append(floor(t, MINUTE));
			a.append(' ');
			a.append('m');
			prependBlank = true;
		}
		t %= MINUTE;
		if (t >= SECOND) {
			if (prependBlank) {
				a.append(' ');
			}
			a.append(floor(t, SECOND));
			a.append(' ');
			a.append('s');
			prependBlank = true;
		}
		t %= SECOND;
		if (t > 0) {
			if (prependBlank) {
				a.append(' ');
			}
			a.append(Integer.toString((int) t));
			a.append(' ');
			a.append('m');
			a.append('s');
		}
		return a.toString();
	}

	public static String calculate_ISO8601(final long l) {
		String result = ISO8601FORMAT.format(new Date(l));
		// convert YYYYMMDDTHH:mm:ss+HH00 into YYYYMMDDTHH:mm:ss+HH:00
		// - note the added colon for the Timezone
		result = result.substring(0, result.length() - 2) + ":" + result.substring(result.length() - 2);
		return result;
	}

	private static String floor(final long d, final long n) {
		return Long.toString(Math.floorDiv(d, n));
	}

}
