"""
Frame for managing observatory database interactions in the GUI.
This module provides functionality to insert, delete, and display observatory 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 FrameObservatories(MyPanel):
    """Panel for managing observatory database operations."""

    def __init__(self, parent, color, row, column, path_default, frame_input, window, **kwargs):
        """Initialize the observatories 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.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 = {
            "Observatory Name": "Name of the ground-based observatory where observations were conducted. Standard names include: La Silla Observatory, Paranal Observatory (VLT), Roque de los Muchachos Observatory (GTC, TNG), Mauna Kea Observatory (Keck, Subaru), etc.",

            "Latitude (degrees)": "Geographic latitude of the observatory in decimal degrees. North latitudes are positive (+), South latitudes are negative (-). Range: -90° to +90°. Example: La Palma (Roque de los Muchachos) = +28.76°, Paranal (VLT) = -24.63°. Precise coordinates are essential for accurate barycentric corrections.",

            "Longitude (degrees)": "Geographic longitude of the observatory in decimal degrees. East longitudes are positive (+), West longitudes are negative (-). Range: -180° to +180°. Example: La Palma = -17.88°, Paranal = -70.40°. Used with latitude for Earth rotation velocity calculations.",

            "Altitude (meters)": "Elevation of the observatory above sea level in meters. High-altitude sites have less atmospheric absorption. Example: La Palma (TNG) = 2387 m, Paranal (VLT) = 2635 m, Mauna Kea = 4205 m. This affects atmospheric corrections and extinction.",

            "Observatory (dropdown)": "Select an existing observatory from the database to display its details or delete it. Only observatories already added to the database appear in this list. These are used during simulated high-resolution data generation and for barycentric velocity calculations."
        }

        # Create help button
        self.help_button = HelpButton(
            self.column1, 0, 0,
            "Observatory Parameters Help",
            help_text,
            columnspan=1
        )
        # Note: no rowspan needed as all widgets are in row 0

        # Observatory name text field
        self.textfield_observatory = MyTextField(
            self.column1, 0, 1, "", "Observatory Name:",
            color=self.color, columnspan=2, width=20
        )

        # Latitude entry
        self.entry_latitude = MyEntry(
            self.column1, 0, 3, "", "Latitude (degrees):", 
            color=self.color, columnspan=2
        )

        # Longitude entry
        self.entry_longitude = MyEntry(
            self.column1, 1, 1, "", "Longitude (degrees):",
            color=self.color, columnspan=2
        )

        # Altitude entry
        self.entry_altitude = MyEntry(
            self.column1, 1, 3, "", "Altitude (meters):",
            color=self.color, columnspan=2
        )

        # Insert button
        self.button_insert_db = MyButton(
            self.column1, 0, 9, 'INSERT OBSERVATORY IN DB', '#FFccaa',
            self.insert_observatory_db, color_panel=self.color, columnspan=2
        )

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

        # Observatories dropdown
        self.dropdown_observatories = MyDropdown(
            self.column2, 0, 1, observatories, "Observatory:", 
            color=self.color, columnspan=2
        )

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

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

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

    def insert_observatory_db(self):
        """Insert a new observatory into the database."""
        DB = DBSQLite3(self.path_default)
        DB.insert_observatory(
            self.textfield_observatory.get_text(),
            float(self.entry_latitude.get_value()),
            float(self.entry_longitude.get_value()),
            float(self.entry_altitude.get_value()),
        )
        
        # Update observatories list
        observatories, _, _, _ = DB.get_observatories()
        DB.close_DB()
        
        # Refresh dropdown
        self.dropdown_observatories.clean_widget()
        self.dropdown_observatories = MyDropdown(
            self.column2, 0, 1, observatories, "Observatory:", 
            color=self.color, columnspan=2
        )
        
        # Update observatory lists in other frames
        self._update_observatory_lists_in_other_frames(observatories)

    def _update_observatory_lists_in_other_frames(self, observatories):
        """Update observatory dropdowns in other frames that use observatory data."""
        try:
            # Update FrameGenerationHRData observatory dropdown
            if hasattr(self.frame_input, 'frame_simulation_HR'):
                self.frame_input.frame_simulation_HR.update_observatory_list(observatories)
        except Exception as e:
            print(f"Error updating observatory lists in other frames: {e}")

    def show_observatory(self):
        """Display details of the selected observatory."""
        observatory = self.dropdown_observatories.get_value()
        DB = DBSQLite3(self.path_default)
        observatory_data = DB.get_observatory_by_key(observatory)
        DB.close_DB()
        
        if observatory_data:
            # Format observatory details
            observatory_details = (
                f"Observatory: {observatory_data[0]}\n"
                f"Latitude: {observatory_data[1]}°\n"
                f"Longitude: {observatory_data[2]}°\n"
                f"Altitude: {observatory_data[3]} m\n"
            )
            self.textfield_observatory_show.insert_text(observatory_details)
        else:
            self.textfield_observatory_show.insert_text("No observatory details found.")

    def delete_observatory_from_db(self):
        """Delete the selected observatory from the database."""
        DB = DBSQLite3(self.path_default)
        DB.delete_observatory_by_key(self.dropdown_observatories.get_value())
        
        # Update observatories list
        observatories, _, _, _ = DB.get_observatories()
        DB.close_DB()
        
        # Refresh dropdown
        self.dropdown_observatories.clean_widget()
        self.dropdown_observatories = MyDropdown(
            self.column2, 0, 1, observatories, "Observatory:", 
            color=self.color, columnspan=2
        )
        
        # Update observatory lists in other frames
        self._update_observatory_lists_in_other_frames(observatories) 