#!/usr/bin/python3

import json
import os
import sys

def read_value_from_file(file_path):
    try:
        with open(file_path, 'r') as file:
            value = file.read().strip()
            return value
    except Exception as e:
        return f"Error: {e}"

def read_click_state(state_file):
    try:
        if os.path.exists(state_file):
            with open(state_file, 'r') as file:
                state = file.read().strip()
                return state == "clicked"
        else:
            return False
    except Exception as e:
        return False

def toggle_click_state(state_file):
    try:
        if read_click_state(state_file):
            with open(state_file, 'w') as file:
                file.write("unclicked")
        else:
            with open(state_file, 'w') as file:
                file.write("clicked")
    except Exception as e:
        pass

def generate_waybar_json(value, clicked):
    if clicked:
        data = {
            "text": value,
            #"tooltip": f"Download Speed: {value}",
            #"class": "custom"
        }
    else:
        data = {
            "text": "DL",
            "tooltip": f"Dpwnload Speed: {value}",
            "class": "custom"
        }
    return json.dumps(data)

if __name__ == "__main__":
    file_path = "/home/teraflops/.config/waybar/scripts/down.txt"
    state_file = "/tmp/waybar_tooltip_state"
    value = read_value_from_file(file_path)

    # Check for the toggle argument
    if len(sys.argv) > 1 and sys.argv[1] == "toggle":
        toggle_click_state(state_file)

    clicked = read_click_state(state_file)
    waybar_json = generate_waybar_json(value, clicked)
    print(waybar_json)

