#!/usr/bin/env python3
"""
UART Control Widget - Integrated
=================================
Command table (left) + UART core widget (right)

Author: Kynsight
Version: 3.0.0
"""

from PyQt6.QtWidgets import QWidget, QHBoxLayout, QSplitter
from PyQt6.QtCore import Qt, pyqtSignal

from command_table.command_table import CommandTableWidget
from uart.uart_kit.uart_core_widget import UARTWidget


class UARTControlWidget(QWidget):
    """
    Integrated UART control widget.
    
    Layout: Command table (left) | UART core (right)
    
    Signals:
        command_sent: (command_id, hex_string)
        packet_received: (packet_info)
        connection_changed: (is_connected)
    """
    
    command_sent = pyqtSignal(int, str)
    packet_received = pyqtSignal(object)
    connection_changed = pyqtSignal(bool)
    
    def __init__(self, db_connection, parent=None):
        super().__init__(parent)
        
        self.conn = db_connection
        
        self._init_ui()
        self._setup_connections()
    
    def _init_ui(self):
        """Initialize UI - side by side layout."""
        layout = QHBoxLayout()
        self.setLayout(layout)
        
        # Splitter for resizable layout
        splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # Left: Command table
        self.command_table = CommandTableWidget(self.conn, 'uart')
        splitter.addWidget(self.command_table)
        
        # Right: UART core widget
        self.uart_core = UARTWidget()
        splitter.addWidget(self.uart_core)
        
        # Set initial sizes (40% table, 60% core)
        splitter.setSizes([400, 600])
        
        layout.addWidget(splitter)
        
        # Initialize ports on startup
        self.uart_core._refresh_ports()
        
        # Table always enabled, CRUD buttons disabled initially (not connected)
        self._update_table_mode(False)
    
    def _setup_connections(self):
        """Connect signals between table and core."""
        
        # Command table → Send via UART (when connected) OR Edit (when disconnected)
        self.command_table.command_double_clicked.connect(self._on_command_double_click)
        
        # UART connection → Change table mode
        self.uart_core.connection_changed.connect(self._on_connection_changed)
        
        # Forward UART signals
        self.uart_core.packet_received.connect(self.packet_received.emit)
    
    def _update_table_mode(self, is_connected):
        """Update table mode based on connection state."""
        if is_connected:
            # Connected mode: CRUD buttons disabled, double-click sends
            self.command_table.btn_add.setEnabled(False)
            self.command_table.btn_edit.setEnabled(False)
            self.command_table.btn_delete.setEnabled(False)
        else:
            # Disconnected mode: CRUD buttons enabled, double-click edits
            self.command_table.btn_add.setEnabled(True)
            # Edit/Delete enabled only if something selected
            has_selection = bool(self.command_table.table.selectedItems())
            self.command_table.btn_edit.setEnabled(has_selection)
            self.command_table.btn_delete.setEnabled(has_selection)
    
    def _on_command_double_click(self, command_id, cmd_data):
        """Handle double-click: Send if connected, Edit if disconnected."""
        if self.uart_core.is_connected:
            # Connected: Send command
            self._send_command(command_id, cmd_data)
        else:
            # Disconnected: Edit command
            self.command_table._edit_command()
    
    def _send_command(self, command_id, cmd_data):
        """Send command via UART."""
        # Get hex string
        hex_string = cmd_data.get('hex_string', '')
        if not hex_string:
            return
        
        # Send via UART core - Use the input field and send button
        try:
            # Set hex string in input field
            self.uart_core.edit_send.setText(hex_string)
            
            # Ensure format is set to Hex
            self.uart_core.combo_format.setCurrentText("Hex")
            
            # Trigger send
            self.uart_core._on_send()
            
            # Emit signal
            self.command_sent.emit(command_id, hex_string)
            
        except Exception as e:
            print(f"Send error: {e}")
    
    def _on_connection_changed(self, is_connected):
        """Handle connection state change."""
        # Update table mode (CRUD buttons, double-click behavior)
        self._update_table_mode(is_connected)
        
        # Forward signal
        self.connection_changed.emit(is_connected)
    
    def get_uart_core(self):
        """Get UART core widget for direct access."""
        return self.uart_core
    
    def get_command_table(self):
        """Get command table for direct access."""
        return self.command_table


if __name__ == "__main__":
    import sys
    from PyQt6.QtWidgets import QApplication
    import sqlite3
    
    app = QApplication(sys.argv)
    
    conn = sqlite3.connect("./database/ehinge.db")
    
    widget = UARTControlWidget(conn)
    widget.setWindowTitle("UART Control - Integrated")
    widget.resize(1400, 800)
    widget.show()
    
    sys.exit(app.exec())
