#!/usr/bin/env python3
"""
Abflug Unified - Connect tab + Map tab in one application.

Single SimulatorDataSource instance shared by both tabs.
Map tab enabled when sim signal received, or when Connect succeeds in ATC mode (fixed position, no sim stream).
"""

import tkinter as tk
from tkinter import ttk
import sys
import os
from typing import Optional

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from simulator_data_source import SimulatorDataSource, DataSourceType
from dpi_utils import configure_tk_dpi, get_safe_window_geometry

# Import after path is set
from abflug_gui import AbflugClientGUI
from rewinger import AircraftTrackerApp

APP_NAME = "Abflug"
APP_VERSION = "3.1.1"


class UnifiedApp:
    """Unified application with Connect and Map tabs."""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title(f"{APP_NAME} v{APP_VERSION}")
        
        configure_tk_dpi(self.root)
        safe_geometry = get_safe_window_geometry(self.root, 1200, 900, 1.0, center=True)
        self.root.geometry(safe_geometry)
        self.root.resizable(True, True)
        
        # Notebook with tabs
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill="both", expand=True, padx=5, pady=5)
        
        # Tab 1: Connect
        self.connect_frame = ttk.Frame(self.notebook, padding="5")
        self.notebook.add(self.connect_frame, text="Connect")
        
        # Tab 2: Map (disabled until sim signal)
        self.map_frame = ttk.Frame(self.notebook, padding="5")
        self.notebook.add(self.map_frame, text="Map")
        self.notebook.tab(1, state="disabled")  # Map tab index 1
        
        # Create Connect tab content first (builds UI with sim source selection)
        # Pass callback to get/create data source when user clicks Connect (uses their autodetect/IP selection)
        self.simulator_data_source = None
        self.connect_tab = AbflugClientGUI(
            self.connect_frame,
            shared_data_source=None,
            on_connected=self._on_connect_tab_connected,
            get_simulator_data_source=self._get_or_create_simulator_data_source
        )
        
        # Create Map tab (will receive shared data source when user clicks Connect)
        self.map_tab = AircraftTrackerApp(
            self.map_frame,
            shared_data_source=None,
            embedded_in_unified=True
        )
        
        # Periodic check: enable Map tab when sim signal received
        self._check_sim_and_enable_map()
        
        # Window close
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)
    
    def _get_or_create_simulator_data_source(self, use_fswidget: bool, fswidget_ip: str, auto_detect: bool):
        """
        Get or create SimulatorDataSource using Connect tab's selection.
        Called when user clicks Connect - ensures autodetect and IP are respected.
        """
        if self.simulator_data_source:
            self.simulator_data_source.stop()
        source_type = DataSourceType.FSWIDGET if use_fswidget else DataSourceType.UDP
        self.simulator_data_source = SimulatorDataSource(
            source_type=source_type,
            udp_port=49002,
            fswidget_ip=fswidget_ip,
            auto_detect=auto_detect
        )
        self.simulator_data_source.start()
        # Pass to Map tab's UDPReceiver (replace its data source)
        if hasattr(self.map_tab, 'udp_receiver') and hasattr(self.map_tab.udp_receiver, 'replace_simulator_data_source'):
            self.map_tab.udp_receiver.replace_simulator_data_source(self.simulator_data_source)
        return self.simulator_data_source
    
    def _on_connect_tab_connected(
        self,
        server_url: str,
        api_key: str,
        observer_lat: Optional[float] = None,
        observer_lon: Optional[float] = None,
    ):
        """Called when Connect tab successfully connects to server."""
        if hasattr(self.map_tab, 'set_http_api_from_client'):
            self.map_tab.set_http_api_from_client(
                server_url, api_key, manual_lat=observer_lat, manual_lon=observer_lon
            )
    
    def _check_sim_and_enable_map(self):
        """Enable Map tab when sim data is received, or when connected in ATC mode (no sim stream)."""
        sim_ok = (
            self.simulator_data_source is not None
            and self.simulator_data_source.is_receiving_data(5.0)
        )
        # ATC mode uses fixed position; SimulatorDataSource may be idle or unused — still allow Map
        ct = self.connect_tab
        atc_ok = bool(
            getattr(ct, "is_connected", False)
            and getattr(ct, "atc_mode_enabled", False)
        )
        if sim_ok or atc_ok:
            self.notebook.tab(1, state="normal")
        self.root.after(1000, self._check_sim_and_enable_map)
    
    def _on_close(self):
        """Clean up on window close."""
        if self.simulator_data_source:
            self.simulator_data_source.stop()
        self.root.destroy()
    
    def run(self):
        self.root.mainloop()


def main():
    app = UnifiedApp()
    app.run()


if __name__ == "__main__":
    main()
