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 energy_full_file = try std.fs.openFileAbsolute("/sys/class/power_supply/BAT0/energy_full", .{});
    defer energy_full_file.close();
    var energy_now_file = try std.fs.openFileAbsolute("/sys/class/power_supply/BAT0/energy_now", .{});
    defer energy_now_file.close();
    var status_file = try std.fs.openFileAbsolute("/sys/class/power_supply/BAT0/status", .{});
    defer status_file.close();

    const energy_full_string = try energy_full_file.reader().readAllAlloc(allocator, 32);
    const energy_now_string = try energy_now_file.reader().readAllAlloc(allocator, 32);
    const status_string = try status_file.reader().readAllAlloc(allocator, 32);
    const energy_full = try std.fmt.parseInt(u32, energy_full_string[0 .. energy_full_string.len - 1], 10);
    const energy_now = try std.fmt.parseInt(u32, energy_now_string[0 .. energy_now_string.len - 1], 10);

    const status = if (std.mem.eql(u8, status_string[0 .. status_string.len - 1], "Full"))
        "="
    else if (std.mem.eql(u8, status_string[0 .. status_string.len - 1], "Discharging"))
        "v"
    else if (std.mem.eql(u8, status_string[0 .. status_string.len - 1], "Charging"))
        "^"
    else
        "?";
    const percent_left = @as(f32, @floatFromInt(energy_now)) / @as(f32, @floatFromInt(energy_full)) * 100;

    return .{
        .full_text = try std.fmt.allocPrint(allocator, "{s} {d:.2}%", .{ status, percent_left }),
    };
}
