const std = @import("std");

// TODO: Maybe it would be good to move date time parsing to separate module

pub fn parseDateTime(datetime: []const u8) ?f64 {
    const time_h = @cImport({
        @cDefine("_XOPEN_SOURCE", "700");
        @cInclude("stddef.h");
        @cInclude("stdio.h");
        @cInclude("time.h");
        @cInclude("timegm.h");
    });

    var buffer: [256]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&buffer);
    var allocator = fba.allocator();

    const datetime_z = allocator.dupeZ(u8, datetime) catch return null;

    var tm: time_h.tm = .{};
    const s = time_h.strptime(datetime_z, "%Y-%m-%dT%H:%M:%S.", &tm);
    if (s == null) {
        return null;
    }

    const s_len = std.mem.len(s);
    if (s[s_len-1] != 'Z') {
        return null;
    }

    const milliseconds_str = s[0..(s_len-1)];
    var milliseconds: f64 = @floatFromInt(std.fmt.parseUnsigned(u32, milliseconds_str, 10) catch return null);
    while (milliseconds >= 1) {
        milliseconds /= 10;
    }

    const seconds: f64 = @floatFromInt(time_h.my_timegm(&tm));

    return seconds + milliseconds;
}

test "parse date time" {
    try std.testing.expectEqual(1723069394.105, parseDateTime("2024-08-07T22:23:14.105Z").?);
}
