const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const Module = @import("../module.zig");
const Self = @This();

cores: usize,
module: Module,

pub fn init(allocator: std.mem.Allocator) !Self {
    var cpuinfo_file = try fs.openFileAbsolute("/proc/cpuinfo", .{});
    defer cpuinfo_file.close();
    const cpuinfo = try cpuinfo_file.reader().readAllAlloc(allocator, 1024 * 128);
    defer allocator.free(cpuinfo);
    const cores = mem.count(u8, cpuinfo, "\n\n");

    return .{
        .cores = cores,
        .module = .{ .getBlockFn = getBlock },
    };
}

pub fn getBlock(module: *Module, allocator: std.mem.Allocator) !Module.Block {
    const self: *const Self = @fieldParentPtr("module", module);

    var loadavg_file = try fs.openFileAbsolute("/proc/loadavg", .{});
    defer loadavg_file.close();

    const loadavg_string = try loadavg_file.reader().readAllAlloc(allocator, 64);
    var loadavg_split = std.mem.splitScalar(u8, loadavg_string[0 .. loadavg_string.len - 1], ' ');
    const loadavg = try std.fmt.parseFloat(f32, loadavg_split.first());

    return .{
        .full_text = try std.fmt.allocPrint(allocator, "{d:0>1.2}", .{loadavg}),
        .severity = @max(0.0, loadavg - @as(f32, @floatFromInt(self.cores))),
    };
}
