/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.util;

import java.math.BigDecimal;
import java.time.Duration;

/**
 * Utility methods for working with time.
 *
 * @author Alex Leigh
 */
public final class TimeUtil {
    public static String toDaysString(final Duration duration) {
        final long days = duration.toDays();
        if (days == 1) return "1 day";
        return days + " days";
    }

    public static int toMillis(Duration d) {
        int nano = d.getNano();
        return nano == 0 ? 0 : nano / 1000000;
    }

    /**
     * Divide one Duration by another while retaining full precision.
     */
    public static long divide(Duration first, Duration second) {
        if (first.isNegative())
            throw new IllegalArgumentException("first may not be negative");
        if (second.isNegative())
            throw new IllegalArgumentException("second may not be negative");
        if (second.isZero())
            throw new IllegalArgumentException("second may not be zero");
        BigDecimal firstDecimal = toSeconds(first);
        BigDecimal secondDecimal = toSeconds(second);
        return firstDecimal.divideToIntegralValue(secondDecimal).longValueExact();
    }

    /**
     * @param duration a duration
     * @return the number of seconds in the duration
     */
    public static BigDecimal toSeconds(Duration duration) {
        return BigDecimal.valueOf(duration.getSeconds()).add(BigDecimal.valueOf(duration.getNano(), 9));
    }
}
