#!/usr/bin/env bash

NEEWER_SDK_PATH="./nate-work/dotfiles/waybar/scripts/neweer_light.py"
NEEWER_MAC="CB:33:40:DF:63:44"
STATE_FILE="$HOME/.cache/neewer_light_state"
BRIGHTNESS_FILE="$HOME/.cache/neewer_brightness"

# Function to get current brightness from cache
get_brightness() {
    if [ -f "$BRIGHTNESS_FILE" ]; then
        cat "$BRIGHTNESS_FILE"
    else
        echo "20"  # Default brightness
    fi
}

# Function to save brightness to cache
save_brightness() {
    echo "$1" > "$BRIGHTNESS_FILE"
}

# Function to get current power state
get_power_state() {
    if [ -f "$STATE_FILE" ]; then
        cat "$STATE_FILE"
    else
        echo "off"  # Default state
    fi
}

# Function to save power state
save_power_state() {
    echo "$1" > "$STATE_FILE"
}

# Function to execute neewer command
execute_neewer() {
    local cmd="$1"
    if [ -n "$NEEWER_MAC" ]; then
        python3 "$NEEWER_SDK_PATH" --mac "$NEEWER_MAC" $cmd
    else
        python3 "$NEEWER_SDK_PATH" $cmd
    fi
}

# Main function for waybar output
waybar_output() {
    local state=$(get_power_state)
    local brightness=$(get_brightness)
    
    if [ "$state" = "on" ]; then
        echo "{\"text\":\"󱣝 ${brightness}%\",\"class\":\"on\",\"tooltip\":\"NEEWER Light: ON (${brightness}%)\"}"
    else
        echo "{\"text\":\"󱣞 OFF\",\"class\":\"off\",\"tooltip\":\"NEEWER Light: OFF\"}"
    fi
}

# Handle different commands
case "$1" in
    "toggle")
        state=$(get_power_state)
        if [ "$state" = "on" ]; then
            execute_neewer "--off" && save_power_state "off"
        else
            execute_neewer "--on" && save_power_state "on"
        fi
        ;;
    "on")
        execute_neewer "--on" && save_power_state "on"
        ;;
    "off")
        execute_neewer "--off" && save_power_state "off"
        ;;
    "brightness")
        if [ -n "$2" ]; then
            brightness="$2"
            execute_neewer "--brightness $brightness" && save_brightness "$brightness"
        fi
        ;;
    "increase")
        current=$(get_brightness)
        new_brightness=$((current + 10))
        if [ $new_brightness -gt 100 ]; then
            new_brightness=100
        fi
        execute_neewer "--brightness $new_brightness" && save_brightness "$new_brightness"
        ;;
    "decrease")
        current=$(get_brightness)
        new_brightness=$((current - 10))
        if [ $new_brightness -lt 0 ]; then
            new_brightness=0
        fi
        execute_neewer "--brightness $new_brightness" && save_brightness "$new_brightness"
        ;;
    "status"|*)
        waybar_output
        ;;
esac
