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

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

BatteryController::~BatteryController() 
{
    
}

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

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

  for (const auto &entry :
       std::filesystem::directory_iterator(powerSupplyPath)) {
    if (entry.is_directory()) {
      std::string bat = entry.path().filename();
      if (bat.find("BAT") != std::string::npos) {
        batteryPath = bat;
      }
    }
  }
}

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();
}
