module analytics.util;

import std.datetime;
import std.array;
import util.data;

SysTime[] generateTimeSeriesTimestamps(Duration intervalSize, int intervalCount) {
    const SysTime now = Clock.currTime(UTC());
    const SysTime endOfToday = SysTime(
        DateTime(now.year, now.month, now.day, 23, 59, 59),
        now.timezone
    );
    SysTime timestamp = endOfToday;
    SysTime[] timestamps = new SysTime[intervalCount + 1];
    timestamps[0] = timestamp;
    for (int i = 0; i < intervalCount; i++) {
        timestamp = timestamp - intervalSize;
        timestamps[i + 1] = timestamp;
    }
    return timestamps;
}

SysTime[] generateTimeSeriesTimestamps(Duration intervalSize, in TimeRange timeRange) {
    SysTime endOfRange;
    SysTime startOfRange;
    if (timeRange.toTime.isNull) {
        endOfRange = Clock.currTime(UTC());
    } else {
        endOfRange = timeRange.toTime.value;
    }
    if (timeRange.fromTime.isNull) {
        startOfRange = endOfRange;
        startOfRange.add!"years"(-5);
    } else {
        startOfRange = timeRange.fromTime.value;
    }

    Appender!(SysTime[]) app;
    app ~= startOfRange;

    SysTime timestamp = startOfRange;
    while (timestamp + intervalSize <= endOfRange) {
        timestamp += intervalSize;
        app ~= timestamp;
    }
    return app[];
}

ulong toUnixMillis(in SysTime ts) {
    return (ts - SysTime(unixTimeToStdTime(0))).total!"msecs";
}

SysTime toSysTime(in ulong unixMillis) {
    return SysTime(unixTimeToStdTime(0)) + msecs(unixMillis);
}
