import curses
import json
import requests
import time

# URL de l'API
url = "http://192.168.1.59/getData"
excluded_keys = {"FW", "PID", "SER#", "TENSIONS", "OR", "HSDS", "XY_ON", "XY_AV", "XY_AC", "XY_AW", "CONS"}

def fetch_data(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return {}

def display_headers(screen, keys, max_width):
    screen.clear()
    for idx, key in enumerate(keys):
        if idx * max_width < curses.COLS:
            try:
                screen.addstr(0, idx * max_width, key.ljust(max_width)[:max_width], curses.color_pair(1))
            except curses.error:
                pass
    screen.refresh()

def display_data(screen, data, keys, line, max_width):
    for idx, key in enumerate(keys):
        if idx * max_width < curses.COLS:
            value_str = str(data.get(key, ""))
            if key == "PPV" and float(value_str) > 0:
                color = curses.color_pair(3)  # Red background for PPV > 0
            else:
                color = curses.color_pair(2)  # Default color
            screen.addstr(line, idx * max_width, value_str.ljust(max_width)[:max_width], color)

    screen.refresh()

def main(screen):
    curses.curs_set(0)  # Hide the cursor
    screen.nodelay(True)  # Don't block waiting for user input
    # Initialize colors
    curses.start_color()
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)  # Header color
    curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)  # Data color
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_CYAN)    # PPV > 0 color

    keys = None
    max_width = 9  # Maximum width for each column

    line = 1
    while True:
        data = fetch_data(url)
        if line == 1: #keys is None:
            keys = [key for key in data.keys() if key not in excluded_keys]
            display_headers(screen, keys, max_width)
        
        try:
            display_data(screen, data, keys, line, max_width)
        except curses.error:
            line = 0
            screen.clear()
            pass
        
        line += 1

        time.sleep(5)

        if screen.getch() != -1:
            break

if __name__ == "__main__":
    curses.wrapper(main)

