#!/bin/bash

BAT_PATH="/sys/class/power_supply/BAT0"
if [ ! -d "$BAT_PATH" ]; then
    echo "Batterie non trouvée"
    exit 1
fi

# Lire les informations
capacity=$(cat "$BAT_PATH/capacity" 2>/dev/null)
status=$(cat "$BAT_PATH/status" 2>/dev/null)
charge_now=$(cat "$BAT_PATH/charge_now" 2>/dev/null)      # µAh
current_now=$(cat "$BAT_PATH/current_now" 2>/dev/null)    # µA
voltage_now=$(cat "$BAT_PATH/voltage_now" 2>/dev/null)    # µV
max_limit=$(cat "$BAT_PATH/charge_control_end_threshold" 2>/dev/null)

# Valeurs par défaut
[ -z "$capacity" ] && capacity=0
[ -z "$status" ] && status="Unknown"
[ -z "$max_limit" ] && max_limit=100

# Calcul de la puissance (si voltage et courant disponibles)
# if [ -n "$voltage_now" ] && [ -n "$current_now" ] && [ "$current_now" -gt 0 ]; then
#     wattage=$(echo "scale=1; $voltage_now * $current_now / 1000000000000" | bc)
# else
#     wattage=""
# fi

wattage=$(cat /tmp/power_now 2>/dev/null)

# Calcul du temps restant (en minutes) si en décharge
time_str=""
if [ "$status" = "Discharging" ] && [ -n "$charge_now" ] && [ -n "$current_now" ] && [ "$current_now" -gt 0 ]; then
    time_h=$(echo "scale=2; $charge_now / $current_now" | bc)
    time_min=$(echo "$time_h * 60" | bc | cut -d. -f1)
    if [ -n "$time_min" ] && [ "$time_min" -gt 0 ]; then
        hours=$(( time_min / 60 ))
        minutes=$(( time_min % 60 ))
        time_str=$(printf "%d:%02d" $hours $minutes)
    fi
fi

# Affichage selon l'état
if [ "$status" = "Charging" ]; then
    icon="⚡"
    if [ -n "$wattage" ]; then
        text="${icon} ${capacity}% (${wattage}W - ${max_limit}%)"
    else
        text="${icon} ${capacity}% (${max_limit}%)"
    fi
elif [ "$status" = "Discharging" ]; then
    # Icône batterie selon le niveau
    if [ $capacity -le 20 ]; then
        icon=""
    elif [ $capacity -le 40 ]; then
        icon=""
    elif [ $capacity -le 60 ]; then
        icon=""
    elif [ $capacity -le 80 ]; then
        icon=""
    else
        icon=""
    fi
    if [ -n "$time_str" ] && [ -n "$wattage" ]; then
        text="${icon} ${capacity}% (${time_str} - ${wattage}W - ${max_limit}%)"
    else
        text="${icon} ${capacity}% (${max_limit}%)"
    fi
else
    icon=""
    if [ -n "$wattage" ]; then
        text="${icon} ${capacity}% (${wattage}W - ${max_limit}%)"
    else
        text="${icon} ${capacity}% (${max_limit}%)"
    fi
fi

echo "$text"
