package be.iminds.ilabt.jfed.experimenter_gui.util;

import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.Deque;
import java.util.LinkedList;

/**
 * User: twalcari
 * Date: 7/3/2014
 * Time: 09:09
 */
public class DateTimeUtils {
    public static final DateTimeFormatter DATE_HOUR_MINUTES_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    public static final DateTimeFormatter DATE_HOUR_MINUTES_SECONDS_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static final int SECONDS = 0;
    public static final int MINUTES = 1;
    public static final int HOURS = 2;
    public static final int DAYS = 3;

    public static int[] getSecondsMinutesHoursDays(Duration duration) {

        int[] result = new int[4];

        long time = duration.getSeconds();
        result[SECONDS] = (int) (time % 60);
        time /= 60;
        result[MINUTES] = (int) (time % 60);
        time /= 60;
        result[HOURS] = (int) (time % 24);
        time /= 24;
        result[DAYS] = (int) time;

        return result;
    }


    public static String prettyPrintDuration(Duration duration) {
        int[] parts = getSecondsMinutesHoursDays(duration);

        Deque<String> stringParts = new LinkedList<>();

        if (parts[DAYS] > 0) {
            stringParts.add(parts[DAYS] + " " + (parts[DAYS] > 1 ? "days" : "day"));
        }
        if (parts[HOURS] > 0) {
            stringParts.add(parts[HOURS] + " " + (parts[HOURS] > 1 ? "hours" : "hour"));
        }
        if (parts[MINUTES] > 0) {
            stringParts.add(parts[MINUTES] + " " + (parts[MINUTES] > 1 ? "minutes" : "minute"));
        }
        if (parts[SECONDS] > 0) {
            stringParts.add(parts[SECONDS] + " " + (parts[SECONDS] > 1 ? "seconds" : "second"));
        }

        if (stringParts.isEmpty()) {
            return "-";
        }

        StringBuilder sb = new StringBuilder();
        sb.append(stringParts.removeLast());

        if (!stringParts.isEmpty()) {
            sb.insert(0, " and ");
            sb.insert(0, stringParts.removeLast());
        }

        while (!stringParts.isEmpty()) {
            sb.insert(0, ", ");
            sb.insert(0, stringParts.removeLast());
        }

        return sb.toString();
    }

}
