"""
Frame for managing instrument database interactions in the GUI.
This module provides functionality to insert, delete, and display instrument details
in the database.
"""

from GUIBRUSHR.GUI.DataInterface.DBSQLite3 import DBSQLite3
from GUIBRUSHR.GUI.LAYOUT.MyPanel import MyPanel
from GUIBRUSHR.GUI.WIDGET.MyButton import MyButton
from GUIBRUSHR.GUI.WIDGET.MyDropDown import MyDropdown
from GUIBRUSHR.GUI.WIDGET.MyEntry import MyEntry
from GUIBRUSHR.GUI.WIDGET.MyLabel import MyLabel
from GUIBRUSHR.GUI.WIDGET.MyTextField import MyTextField
from GUIBRUSHR.General_Constants.FunctionsAndConstants.Constant_Variables import ConstantVariables
from GUIBRUSHR.General_Constants.Classes.HelpButton import HelpButton


class FrameInstrument(MyPanel):
    """Panel for managing instrument database operations."""

    def __init__(self, parent, color, row, column, path_default, frame_input, window, **kwargs):
        """Initialize the instrument frame panel.
        
        Args:
            parent: Parent widget
            color: Background color
            row: Row position
            column: Column position
            path_default: Default path for database
            frame_input: Input frame reference
            window: Main window reference
            **kwargs: Additional keyword arguments
        """
        super().__init__(parent, color, row, column, **kwargs)
        
        # Store instance variables
        self.dropdown_instruments = None
        self.path_folder_targets = frame_input.frame_path.path_folder_targets.get_text()
        self.global_exc = 0
        self.frame_input = frame_input
        self.path_default = path_default
        self.window = window
        self.color = color
        self.parent = parent

        # Initialize panel columns
        self._init_columns()
        
        # Initialize column 1 widgets
        self._init_column1_widgets()
        
        # Initialize column 2 widgets
        self._init_column2_widgets()

    def _init_columns(self):
        """Initialize the three column panels."""
        self.column1 = MyPanel(self, self.color, 0, 1)
        self.column2 = MyPanel(self, self.color, 0, 2)
        self.column3 = MyPanel(self, self.color, 0, 3)

    def _init_column1_widgets(self):
        """Initialize widgets for column 1."""
        # Help text dictionary
        help_text = {
            "Instrument": "Name of the spectroscopic instrument. Must exactly match the folder name used in your target directory structure. For instruments with special characters or spaces, use underscores. Example: 'GIANO-B' becomes 'GIANO_B'.",

            "Resolution": "Spectral resolution category: 'HR' (High Resolution, R > 20,000, e.g., HARPS, ESPRESSO, GIANO-B) for Doppler spectroscopy and atmospheric line detection. 'LR' (Low Resolution, R < 1,000, e.g., HST/WFC3, JWST/NIRISS) for transmission/emission spectroscopy with broad spectral features.",

            "Inst. HWHM (km/s)": "Instrument's spectral resolution expressed as Half-Width at Half-Maximum in km/s. This is the velocity width of the instrument profile and sets the intrinsic velocity blur. For high-resolution: typically 1-3 km/s. For low-resolution (not needed): tens to hundreds of km/s. Used for model convolution during cross-correlation.",

            "Min. WL instrument (μm)": "Minimum wavelength coverage of the instrument in micrometers. Defines the blue edge of the spectral range. Example: HARPS ~0.38 μm (optical), GIANO-B ~0.95 μm (near-IR), JWST/NIRSpec ~0.6 μm.",

            "Max. WL instrument (μm)": "Maximum wavelength coverage of the instrument in micrometers. Defines the red edge of the spectral range. Example: HARPS ~0.69 μm (optical), GIANO-B ~2.45 μm (near-IR), JWST/NIRSpec ~5.3 μm.",

            "Instrument (dropdown)": "Select an existing instrument from the database to display its details or delete it. Only instruments already added to the database appear in this list."
        }

        # Create help button
        self.help_button = HelpButton(
            self.column1, 0, 0,
            "Instrument Parameters Help",
            help_text,
            columnspan=1
        )
        self.help_button.button.grid(rowspan=2)  # Span across both rows

        # Instrument text field
        self.textfield_instrument = MyTextField(
            self.column1, 0, 1, "", "Instrument:",
            color=self.color, columnspan=3, width=30
        )

        # Resolution dropdown
        self.dropdown_resolution = MyDropdown(
            self.column1, 0, 4, ConstantVariables.LIST_RESOLUTION_DB,
            "Resolution:", color=self.color, columnspan=2
        )

        # HWHM entry
        self.entry_pixel_dv = MyEntry(
            self.column1, 0, 6, "", "Inst. HWHM (km/s):", 
            color=self.color, columnspan=2
        )

        # Information label
        # self.label_info = MyLabel(
        #     self.column1, 1, 3, self.color,
        #     """Use the same name you use for the folders inside the Target file.     \n
        #     For Instruments that contains special characters or spaces use '_':    \n
        #     Example: GIANO-B will be written as GIANO_B
        #     """, columnspan=3
        # )

        # Wavelength entries
        self.entry_min_wl = MyEntry(
            self.column1, 1, 1, "", "Min. WL instrument (μm):",
            color=self.color, columnspan=2
        )
        self.entry_max_wl = MyEntry(
            self.column1, 1, 3, "", "Max. WL instrument (μm):",
            color=self.color, columnspan=2
        )

        # Insert button
        self.button_insert_db = MyButton(
            self.column1, 1, 8, 'INSERT INSTRUMENT IN DB', '#FFccaa',
            self.insert_instrument_db, color_panel=self.color, columnspan=2
        )

    def _init_column2_widgets(self):
        """Initialize widgets for column 2."""
        # Get instruments from database
        DB = DBSQLite3(self.path_default)
        instruments, _, _, _, _ = DB.get_instruments()
        DB.close_DB()

        # Instruments dropdown
        self.dropdown_instruments = MyDropdown(
            self.column2, 0, 1, instruments, "Instrument:", 
            color=self.color, columnspan=2
        )

        # Delete button
        self.button_delete_db = MyButton(
            self.column2, 0, 3, 'DELETE INSTRUMENT FROM DB', '#f7311b',
            self.delete_instrument_from_db, color_panel=self.color, columnspan=2
        )

        # Display button
        self.button_show_db = MyButton(
            self.column2, 1, 1, 'DISPLAY\nINSTRUMENT\nDETAILS', '#a066f2',
            self.show_instrument, color_panel=self.color, columnspan=2
        )

        # Details text field
        self.textfield_instrument_show = MyTextField(
            self.column2, 1, 3, "", "Instrument\ndetails:", 
            color=self.color, columnspan=2, width=30, height=5
        )

    def insert_instrument_db(self):
        """Insert a new instrument into the database."""
        DB = DBSQLite3(self.path_default)
        DB.insert_instrument(
            self.textfield_instrument.get_text(),
            self.dropdown_resolution.get_value(),
            str(self.entry_pixel_dv.get_value()),
            str(self.entry_min_wl.get_value()),
            str(self.entry_max_wl.get_value()),
        )
        
        # Update instruments list
        instruments, _, _, _, _ = DB.get_instruments()
        DB.close_DB()
        
        # Refresh dropdown
        self.dropdown_instruments.clean_widget()
        self.dropdown_instruments = MyDropdown(
            self.column2, 0, 1, instruments, "Instrument:", 
            color=self.color, columnspan=2
        )
        
        # Update parent frame
        self.parent.frame_target.modify_list_instrument(instruments)

    def show_instrument(self):
        """Display details of the selected instrument."""
        instrument = self.dropdown_instruments.get_value()
        DB = DBSQLite3(self.path_default)
        instrument_obj = DB.get_instrument_by_key(instrument)
        DB.close_DB()
        
        # Format instrument details
        instrument_details = (
            f"Instrument: {instrument_obj.name}\n"
            f"Resolution: {instrument_obj.resolution}\n"
            f"HWHM: {instrument_obj.hwhm_km_s} km/s\n"
            f"WL min: {instrument_obj.wl_min}\n"
            f"WL max: {instrument_obj.wl_max}\n"
        )
        self.textfield_instrument_show.insert_text(instrument_details)

    def delete_instrument_from_db(self):
        """Delete the selected instrument from the database."""
        DB = DBSQLite3(self.path_default)
        DB.delete_instrument_by_key(self.dropdown_instruments.get_value())
        
        # Update instruments list
        instruments, _, _, _, _ = DB.get_instruments()
        DB.close_DB()
        
        # Refresh dropdown
        self.dropdown_instruments.clean_widget()
        self.dropdown_instruments = MyDropdown(
            self.column2, 0, 1, instruments, "Instrument:", 
            color=self.color, columnspan=2
        )
        
        # Update parent frame
        self.parent.frame_target.modify_list_instrument(instruments)
