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

module: Module,

pub fn init(allocator: std.mem.Allocator) !Self {
    _ = allocator;
    return .{
        .module = .{ .getBlockFn = getBlock },
    };
}

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

    var meminfo_file = try std.fs.openFileAbsolute("/proc/meminfo", .{});
    defer meminfo_file.close();

    const meminfo_string = try meminfo_file.reader().readAllAlloc(allocator, 4096);
    const mem_total_idx = std.mem.indexOf(u8, meminfo_string, "MemTotal:");
    const mem_available_idx = std.mem.indexOf(u8, meminfo_string, "MemAvailable:");
    const mem_total_newline = std.mem.indexOfScalarPos(u8, meminfo_string, mem_total_idx.?, '\n');
    const mem_available_newline = std.mem.indexOfScalarPos(u8, meminfo_string, mem_available_idx.?, '\n');
    var mem_total_split = std.mem.splitBackwardsScalar(u8, meminfo_string[mem_total_idx.?..mem_total_newline.?], ' ');
    var mem_available_split = std.mem.splitBackwardsScalar(u8, meminfo_string[mem_available_idx.?..mem_available_newline.?], ' ');
    _ = mem_total_split.next();
    _ = mem_available_split.next();

    const mem_total: f32 = @floatFromInt(try std.fmt.parseInt(usize, mem_total_split.next().?, 10));
    const mem_available: f32 = @floatFromInt(try std.fmt.parseInt(usize, mem_available_split.next().?, 10));
    const mem = mem_total - mem_available;

    return .{
        .full_text = try std.fmt.allocPrint(allocator, "{d:.3}/{d:.0} GB", .{ mem / 1000 / 1000, mem_total / 1000 / 1000 }),
    };
}
