#include <batterycontroller.h>
#include <fstream>
#include <filesystem>
#include <iostream>

BatteryController::BatteryController() 
{
    findBatteryPath();
}

BatteryController::~BatteryController() 
{
    
}

void BatteryController::findBatteryPath() {
    batteryPath.clear();

    const std::string powerSupplyPath = "/sys/class/power_supply/";

    std::error_code ec;
    for (const auto &entry : std::filesystem::directory_iterator(powerSupplyPath, ec)) {
        if (ec) {
            std::cerr << "Failed to iterate power supply directory: " << ec.message() << std::endl;
            break;
        }

        if (entry.is_directory(ec)) {
            std::string bat = entry.path().filename();
            if (bat.find("BAT") != std::string::npos) {
                batteryPath = bat;
                break;
            }
        }
    }
}

int BatteryController::getBatteryLevel()
{
    if (batteryPath.empty())
    {
        findBatteryPath();
    }

    std::ifstream batteryFile("/sys/class/power_supply/" + batteryPath + "/capacity");
    if (batteryFile.is_open())
    {
        int level;
        batteryFile >> level;
        return level;
    }
    batteryFile.close();

    return -1;
}

BatteryController::BatteryStatus BatteryController::getBatteryStatus()
{
    if (batteryPath.empty())
    {
        findBatteryPath();
    }

    std::ifstream batteryFile("/sys/class/power_supply/" + batteryPath + "/status");
    if (batteryFile.is_open())
    {
        std::string status;
        batteryFile >> status;
        if (status == "Charging")
        {
            return BatteryStatus::Charging;
        }
        else if (status == "Discharging")
        {
            return BatteryStatus::Discharging;
        }
        else if (status == "Full")
        {
            return BatteryStatus::Full;
        }
        else
        {
            return BatteryStatus::Unknown;

        }
    }
    return BatteryStatus();
}
