#!/usr/bin/env python3
"""
Standalone drawer CLI — connects directly to the PLC via ADS.
Subscribes to drawer state changes and prints them in real time.

Commands: <number> to unlock, <number>l to lock, q to quit.
"""

import sys
from ctypes import sizeof

import pyads
import mysql.connector

PLC_IP = "192.168.212.11"
PLC_AMS_NET_ID = "5.165.49.92.1.1"

DB_HOST = "127.0.0.1"
DB_PORT = 3306
DB_NAME = "median"
DB_USER = "root"
DB_PASS = "Median1"


def _parse_drawer_id(variable_name: str, suffix: str):
    try:
        if "MAIN.Drawer_" in variable_name and suffix in variable_name:
            return int(variable_name.split("MAIN.Drawer_")[1].split(suffix)[0])
    except (IndexError, ValueError):
        pass
    return None


def update_db(drawer_id: int, opened: bool):
    try:
        x_adr = f"P01.{drawer_id:3d}"
        x_etat = "U" if opened else "L"
        conn = mysql.connector.connect(host=DB_HOST, port=DB_PORT, database=DB_NAME, user=DB_USER, password=DB_PASS)
        cursor = conn.cursor()
        cursor.execute("UPDATE f_adr SET x_etat = %s WHERE x_adr = %s", (x_etat, x_adr))
        conn.commit()
        cursor.close()
        conn.close()
        print(f"\n  [db] {x_adr} → {x_etat}")
        print("Command: ", end="", flush=True)
    except Exception as e:
        print(f"\n  [db error] {e}")
        print("Command: ", end="", flush=True)


def make_callback(suffix, label, connection):
    def callback(notification, data):
        try:
            _, _, value = connection.parse_notification(notification, pyads.PLCTYPE_BOOL)
            drawer_id = _parse_drawer_id(data, suffix)
            if drawer_id is not None:
                state = "ON" if value else "OFF"
                print(f"\n  [event] Drawer {drawer_id:02d} {label}: {state}")
                print("Command: ", end="", flush=True)
                if suffix == ".API_OPEN_MED":
                    update_db(drawer_id, opened=value)
        except Exception:
            pass
    return callback


def setup_notifications(connection, drawer_count):
    handles = []
    attr = pyads.NotificationAttrib(sizeof(pyads.PLCTYPE_BOOL))
    subscriptions = [
        (".API_LOCKED_MED",   "locked"),
        (".API_OPEN_MED",     "opened"),
        (".MED_REQ_UNL_API",  "unlock_req"),
    ]
    for drawer_id in range(1, drawer_count + 1):
        for suffix, label in subscriptions:
            var = f"MAIN.Drawer_{drawer_id:02d}{suffix}"
            cb = make_callback(suffix, label, connection)
            handle = connection.add_device_notification(var, attr, cb)
            handles.append(handle)
    return handles


def clear_notifications(connection, handles):
    for handle in handles:
        try:
            connection.del_device_notification(*handle) if isinstance(handle, tuple) else connection.del_device_notification(handle)
        except Exception:
            pass


def read_drawer_state(connection, drawer_id: int) -> str:
    try:
        locked = connection.read_by_name(f"MAIN.Drawer_{drawer_id:02d}.API_LOCKED_MED", pyads.PLCTYPE_BOOL)
        opened = connection.read_by_name(f"MAIN.Drawer_{drawer_id:02d}.API_OPEN_MED", pyads.PLCTYPE_BOOL)
        lock_str = "locked" if locked else "unlocked"
        open_str = "opened" if opened else "closed"
        return f"{lock_str}, {open_str}"
    except Exception:
        return "state unknown"


def set_drawer(connection, drawer_id: int, unlock: bool):
    state = read_drawer_state(connection, drawer_id)
    var = f"MAIN.Drawer_{drawer_id:02d}.MED_REQ_UNL_API"
    connection.write_by_name(var, unlock, pyads.PLCTYPE_BOOL)
    action = "Unlock" if unlock else "Lock"
    print(f"  Drawer {drawer_id} ({state}) → {action} sent.")


def main():
    print(f"Connecting to PLC at {PLC_IP} ({PLC_AMS_NET_ID})...")
    connection = pyads.Connection(PLC_AMS_NET_ID, pyads.PORT_TC3PLC1, PLC_IP)

    try:
        connection.open()
        drawer_count = connection.read_by_name("GC.GC_DRAWER_COUNT", pyads.PLCTYPE_INT)
        print(f"Connected. {drawer_count} drawers available.")

        handles = setup_notifications(connection, drawer_count)
        print(f"Subscribed to {len(handles)} notifications.")
        print("Commands: <number> to unlock, <number>l to lock, q to quit.\n")

        while True:
            try:
                raw = input("Command (q to quit, <n> to unlock drawer, <n>l to lock): ").strip().lower()
                if raw == "q":
                    break
                lock = raw.endswith("l")
                raw_id = raw.rstrip("l")
                drawer_id = int(raw_id)
                if not 1 <= drawer_id <= drawer_count:
                    print(f"  Please enter a number between 1 and {drawer_count}.")
                    continue
                set_drawer(connection, drawer_id, unlock=not lock)
            except ValueError:
                print("  Invalid input.")
            except KeyboardInterrupt:
                break

    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
    finally:
        clear_notifications(connection, handles if "handles" in dir() else [])
        connection.close()
        print("Disconnected.")


if __name__ == "__main__":
    main()
