package com.atlassian.bitbucket.mesh.throttle;

import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

public class ThrottlingOutputUtils {

    private static final long DAY_MS = TimeUnit.DAYS.toMillis(1);
    private static final long MINUTE_MS = TimeUnit.MINUTES.toMillis(1);

    public static DecimalFormat newBriefNumberFormat() {
        return new DecimalFormat("#.##");
    }

    public static String toHumanDuration(long millis) {
        StringBuilder builder = new StringBuilder();
        long remaining = millis;
        remaining = appendPeriod(builder, remaining, TimeUnit.DAYS, "d");
        remaining = appendPeriod(builder, remaining, TimeUnit.HOURS, "h");
        remaining = appendPeriod(builder, remaining, TimeUnit.MINUTES, "m");
        if (millis >= DAY_MS) {
            //Don't include second resolution if the total time is > 1 day
            return builder.toString();
        }
        remaining = appendPeriod(builder, remaining, TimeUnit.SECONDS, "s");
        if (millis >= MINUTE_MS) {
            //Don't include millisecond resolution if the total time is > 1 minute
            return builder.toString();
        }
        appendPeriod(builder, remaining, TimeUnit.MILLISECONDS, "ms");

        return builder.toString();
    }

    public static String toHumanDuration(long duration, TimeUnit timeUnit) {
        return toHumanDuration(timeUnit.toMillis(duration));
    }

    private static long appendPeriod(StringBuilder builder, long millis, TimeUnit timeUnit, String unitString) {
        long units = timeUnit.convert(millis, TimeUnit.MILLISECONDS);
        if (units > 0 || builder.length() > 0) {
            builder.append(units).append(unitString);
        }
        return millis - timeUnit.toMillis(units);
    }
}
