# src/controllers/device_controller.py
from PyQt5.QtWidgets import QWidget, QListWidgetItem
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import Qt
import os

from src.services.device_service import check_available_device
from src.config import UXUI_ASSETS, DongleModelMap, DongleIconMap

class DeviceController:
    def __init__(self, main_window):
        self.main_window = main_window
        self.selected_device = None
        self.connected_devices = []

    def refresh_devices(self):
        """Refresh the list of connected devices"""
        try:
            print("Refreshing devices...")
            device_descriptors = check_available_device()
            self.connected_devices = []
            # print(self.connected_devices)

            if device_descriptors.device_descriptor_number > 0:
                self.parse_and_store_devices(device_descriptors.device_descriptor_list)
                self.display_devices(device_descriptors.device_descriptor_list)
                return True
            else:
                self.main_window.show_no_device_gif()
                return False
        except Exception as e:
            print(f"Error in refresh_devices: {e}")
            return False

    def parse_and_store_devices(self, devices):
        """Parse device information and store it"""
        for device in devices:
            try:
                product_id = hex(device.product_id).strip().lower()
                dongle = DongleModelMap.get(product_id, "unknown")
                device.dongle = dongle

                new_device = {
                    'usb_port_id': device.usb_port_id,
                    'product_id': device.product_id,
                    'kn_number': device.kn_number,
                    'dongle': dongle
                }
                
                existing_device_index = next(
                    (index for (index, d) in enumerate(self.connected_devices)
                    if d['usb_port_id'] == new_device['usb_port_id']),
                    None
                )
                
                if existing_device_index is not None:
                    self.connected_devices[existing_device_index] = new_device
                else:
                    self.connected_devices.append(new_device)
            except Exception as e:
                print(f"Error processing device: {e}")

    def display_devices(self, devices):
        """Display the connected devices in the UI"""
        try:
            if not hasattr(self.main_window, 'device_list_widget'):
                print("Warning: main_window does not have device_list_widget attribute")
                return
                
            self.main_window.device_list_widget.clear()
            
            if not devices:
                print("No devices to display")
                return
                
            for device in devices:
                try:
                    product_id = hex(device.product_id).strip().lower()
                    icon_path = os.path.join(UXUI_ASSETS, DongleIconMap.get(product_id, "unknown_dongle.png"))
                    
                    item = QListWidgetItem()
                    item.setData(Qt.UserRole, device)
                    
                    pixmap = QPixmap(icon_path)
                    icon = QIcon(pixmap)  # Convert QPixmap to QIcon
                    item.setIcon(icon)
                    
                    # Set device name as the display text
                    dongle_name = DongleModelMap.get(product_id, "Unknown Device")
                    item.setText(f"{dongle_name} (KN: {device.kn_number})")
                    
                    self.main_window.device_list_widget.addItem(item)
                    print(f"Added device to list: {dongle_name} (KN: {device.kn_number})")
                except Exception as e:
                    print(f"Error adding device to list: {e}")
        except Exception as e:
            print(f"Error in display_devices: {e}")

    def get_devices(self):
        """Get the list of connected devices"""
        try:
            device_descriptors = check_available_device()
            if device_descriptors.device_descriptor_number > 0:
                # Parse and store devices to ensure connected_devices is updated
                self.parse_and_store_devices(device_descriptors.device_descriptor_list)
                return device_descriptors.device_descriptor_list
            return []
        except Exception as e:
            print(f"Error in get_devices: {e}")
            return []

    def get_selected_device(self):
        """Get the currently selected device"""
        return self.selected_device

    def select_device(self, device, list_item, list_widget):
        """Select a device and update UI"""
        self.selected_device = device
        print("Selected dongle:", device)
        
        # Update list item visual selection
        for index in range(list_widget.count()):
            item = list_widget.item(index)
            widget = list_widget.itemWidget(item)
            if widget:  # Check if widget exists before setting style
                widget.setStyleSheet("background: none;")
        
        list_item_widget = list_widget.itemWidget(list_item)
        if list_item_widget:  # Check if widget exists before setting style
            list_item_widget.setStyleSheet("background-color: lightblue;")