import { buildIntervalData, populateData } from './interval-forge';
import { IntervalUnitArray, IntervalUnitSecondFactors, IntervalUnitDescArray } from './interval-common';
export class Interval {
    seconds;
    static from(input) {
        return new Interval(input);
    }
    constructor(input) {
        const data = buildIntervalData(input);
        populateData(data, this);
    }
    toMilliseconds() {
        return this.toSeconds() * 1000;
    }
    toSeconds() {
        if (this.seconds !== undefined) {
            return this.seconds;
        }
        const seconds = intervalToSeconds(this);
        this.seconds = seconds;
        return seconds;
    }
    toMinutes() {
        return this.toSeconds() / 60;
    }
    toHours() {
        return this.toSeconds() / 3600;
    }
    isEqual(interval) {
        return this.toMilliseconds() === interval.toMilliseconds();
    }
    toString() {
        return intervalDump(this) || '';
    }
}
export function intervalSum(intervalArgs) {
    const outputData = {};
    IntervalUnitArray.forEach((unit) => {
        outputData[unit] = 0;
    });
    let direction;
    let data;
    intervalArgs.forEach((interval) => {
        data = buildIntervalData(interval);
        direction = data.inversed ? -1 : 1;
        IntervalUnitArray.forEach((unit) => {
            outputData[unit] += data[unit] * direction;
        });
    });
    return new Interval(outputData);
}
export function intervalToSeconds(data) {
    let seconds = 0;
    let unit;
    for (unit in IntervalUnitSecondFactors) {
        seconds += data[unit] * IntervalUnitSecondFactors[unit] || 0;
    }
    return seconds;
}
export function intervalDump(data) {
    let intervalStr = '';
    IntervalUnitDescArray.forEach((unit) => {
        if (data[unit]) {
            intervalStr += String(data[unit]) + unit;
        }
    });
    if (intervalStr) {
        return (data.inversed ? '-' : '') + intervalStr;
    }
    return null;
}
