from template import create_gui
from data import EnduranceDataManager
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import time
from tkinter import PhotoImage
from logger import start_per_valve_logger
from graphViewer import GraphViewer



# Instantiate GUI and data manager
root, connect_btn, disconnect_btn, graph_btn, valve_tree, pressure_labels, flow_labels, pump_rpm_label = create_gui()
data_mgr = EnduranceDataManager()
status_icons = {
    "OPERATIONAL": PhotoImage(file="icons/green.png"),
    "PRE-OPERATIONAL": PhotoImage(file="icons/yellow.png"),
    "UNKNOWN": PhotoImage(file="icons/red.png"),
}
image_refs = []  # Needed to prevent garbage collection of images

# === Update the GUI based on data manager ===
def refresh_gui():
    if not data_mgr.connected:
        root.after(1000, refresh_gui)
        return

   # data_mgr.simulate_update()  # Replace with live update later

    valve_tree.delete(*valve_tree.get_children())
    image_refs.clear()  # Clear old references

    valve_data = data_mgr.get_valve_data()
    for node_id, data in valve_data.items():
        status = data.get("status", "UNKNOWN")
        icon = status_icons.get(status, status_icons["UNKNOWN"])
        image_refs.append(icon)  # prevent GC

        valve_tree.insert("", "end", image=icon, values=(
            data["node_id"],
            data["serial"],
            data["setpoint"],
            data["feedback"],
            data["drift"],
        ))


    # Update pressure sensors
    pressure_data = data_mgr.get_pressure_data()
    for i, lbl in enumerate(pressure_labels):
        raw = pressure_data.get(f'0x{i+1:02X}', 0)
        value = float(raw) / 100.0  # assuming raw is in centibar
        lbl.config(text=f"Pressure {i+1}: {value:.2f} bar")

    # Update flowmeters (scaled to L/h)
    flow_data = data_mgr.get_flow_data()
    for i, lbl in enumerate(flow_labels):
        raw = flow_data.get(f'0x{i+1:02X}', 0)
        value = float(raw) / 100.0
        lbl.config(text=f"Flowmeter {i+1}: {value:.1f} L/h")

    # Update pump RPM
    pump_rpm_label.config(text=str(data_mgr.get_pump_rpm()))

    root.after(1000, refresh_gui)

# === Button Callbacks ===
def handle_connect():
    data_mgr.connect_to_can()
    connect_btn.config(state=DISABLED)
    disconnect_btn.config(state=NORMAL)

def handle_disconnect():
    data_mgr.disconnect()
    connect_btn.config(state=NORMAL)
    disconnect_btn.config(state=DISABLED)
    valve_tree.delete(*valve_tree.get_children())

# Bind buttons
connect_btn.config(command=handle_connect)
disconnect_btn.config(command=handle_disconnect)
disconnect_btn.config(state=DISABLED)

def main():
    refresh_gui()
    root.mainloop()

if __name__ == "__main__":
    start_per_valve_logger(data_mgr)
    graph_btn.config(command=lambda: GraphViewer(root))
    main()
