# radar_data_reader/gui/rec_config_window.py

"""
GUI Window for editing the configuration for the g_reconvert.exe runner.
This version is now a lightweight wrapper around the GReconverterOptionsFrame.
"""

import tkinter as tk
from tkinter import ttk, filedialog
from typing import Dict, Any, Callable
import os

from .gui_utils import center_window
from .config_frames import GReconverterOptionsFrame


class RecConfigWindow(tk.Toplevel):
    """A Toplevel window for managing g_reconvert.exe parameters."""

    def __init__(
        self,
        master,
        controller,
        current_config: Dict[str, Any],
        title: str,
        save_command: Callable[[Dict[str, Any]], None],
    ):
        super().__init__(master)
        self.controller = controller
        self.config_data = current_config.copy()
        self.window_title = title
        self.save_callback = save_command

        self.withdraw()
        self._init_window()
        self._init_vars()
        self._populate_vars_from_config()
        self._create_widgets()

        center_window(self, self.master)
        self.protocol("WM_DELETE_WINDOW", self._on_cancel)

    def _init_window(self):
        self.title(self.window_title)
        self.geometry("800x650")
        self.transient(self.master)

    def _init_vars(self):
        """Initializes all Tkinter variables for the parameters."""
        self.vars = {
            "cpp_executable_path": tk.StringVar(),
            "analyze_only": tk.BooleanVar(),
            "no_sign": tk.BooleanVar(),
            "use_fw_header": tk.BooleanVar(),
            "fix_dsp_bug": tk.BooleanVar(),
            "sync_signal_flows": tk.BooleanVar(),
            "extract_sw_only": tk.BooleanVar(),
            "extract_dsp_only": tk.BooleanVar(),
            "stop_on_discontinuity": tk.BooleanVar(),
            "dry_run": tk.BooleanVar(),
            "start_from_stby": tk.BooleanVar(),
            "fix_sata_date": tk.BooleanVar(),
            "examine_data": tk.BooleanVar(),
            "post_process": tk.BooleanVar(),
            "post_process_level": tk.StringVar(),
            "output_format": tk.StringVar(),
            "json_config_file": tk.StringVar(),
            "max_batches": tk.StringVar(),
            "pri_number": tk.StringVar(),
            "rbin_number": tk.StringVar(),
            "video_out_to_rec": tk.BooleanVar(),
            "video_show": tk.BooleanVar(),
            "video_save": tk.BooleanVar(),
            "video_fix_framerate": tk.BooleanVar(),
            "gps_save_track": tk.BooleanVar(),
            "fix_hr_debug": tk.BooleanVar(),
            "sar_save_only": tk.BooleanVar(),
            "video_add_subtitles": tk.BooleanVar(),
            "verbose": tk.BooleanVar(),
            "debug_messages": tk.BooleanVar(),
            "quiet": tk.BooleanVar(),
            "mask_warnings": tk.BooleanVar(),
            "mask_errors": tk.BooleanVar(),
            "silent_overwrite": tk.BooleanVar(),
            "enable_python_worker_profiling": tk.BooleanVar(),
        }

    def _populate_vars_from_config(self):
        for key, var in self.vars.items():
            if key in self.config_data:
                var.set(self.config_data.get(key, ""))  # Usa un default per sicurezza

    def _create_widgets(self):
        main_frame = ttk.Frame(self, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        exe_frame = ttk.LabelFrame(main_frame, text="Executable Path")
        exe_frame.pack(fill=tk.X, pady=(0, 10))
        exe_frame.columnconfigure(0, weight=1)

        exe_entry = ttk.Entry(exe_frame, textvariable=self.vars["cpp_executable_path"])
        exe_entry.grid(row=0, column=0, sticky="ew", padx=5, pady=5)

        browse_button = ttk.Button(
            exe_frame, text="Browse...", command=self._select_executable_path
        )
        browse_button.grid(row=0, column=1, padx=5, pady=5)

        options_frame = GReconverterOptionsFrame(main_frame, self.vars)
        options_frame.pack(fill=tk.BOTH, expand=True)

        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(10, 0))

        ttk.Button(button_frame, text="Save & Close", command=self._on_save).pack(
            side=tk.RIGHT, padx=5
        )
        ttk.Button(button_frame, text="Cancel", command=self._on_cancel).pack(
            side=tk.RIGHT
        )

    def _select_executable_path(self):
        filetypes = (
            [("Executable", "*.exe"), ("All files", "*.*")]
            if os.name == "nt"
            else [("All files", "*")]
        )
        filepath = filedialog.askopenfilename(
            title="Select g_reconvert Executable", filetypes=filetypes
        )
        if filepath:
            self.vars["cpp_executable_path"].set(filepath)

    def _on_save(self):
        new_config = {key: var.get() for key, var in self.vars.items()}
        self.save_callback(new_config)
        self.destroy()

    def _on_cancel(self):
        self.destroy()
