import { bind } from "astal";
import Battery from "gi://AstalBattery";

export const BatteryBox = () => {
    const battery = Battery.get_default();
    const batteryEnergy = (energyRate: number) => {
        return energyRate > 0.1 ? `${Math.round(energyRate * 10) / 10} W ` : "";
    };
    return (
        <box
            cssClasses={["battery-info"]}
            visible={bind(battery, "isBattery")}
            hexpand={false}
            vexpand={false}
        >
            <image
                iconName={bind(battery, "batteryIconName")}
                tooltipText={bind(battery, "energyRate").as(er =>
                    batteryEnergy(er),
                )}
            />
            <label
                label={bind(battery, "percentage").as(
                    p => ` ${Math.round(p * 100)}%`,
                )}
                marginEnd={3}
            />
            <label
                cssClasses={["battery-time"]}
                visible={bind(battery, "charging").as(c => !c)}
                label={bind(battery, "timeToEmpty").as(t => `(${toTime(t)})`)}
                tooltipText={bind(battery, 'energyRate').as(er => `Time to empty. Power usage: ${batteryEnergy(er)}`)}
            />
            <label
                cssClasses={["battery-time"]}
                visible={bind(battery, "charging")}
                label={bind(battery, "timeToFull").as(t => `(${toTime(t)})`)}
                tooltipText={bind(battery, 'energyRate').as(er => `Time to full. Charge rate: ${batteryEnergy(er)}`)}
            />
        </box>
    );
};

const MINUTE = 60;
const HOUR = MINUTE * 60;
const toTime = (time: number) => {
    if (!time) return "Waiting on BIOS"
    if (time > 24 * HOUR) return "24h+";

    const hours = Math.round(time / HOUR);
    const minutes = Math.round((time - hours * HOUR) / MINUTE);

    const hoursDisplay = hours > 0 ? `${hours}h` : "";
    const minutesDisplay = minutes > 0 ? `${minutes}m` : "";

    return `${hoursDisplay}${minutesDisplay}`;
};
