# radar_data_reader/gui/segment_export_config_window.py

"""
GUI Window for editing the complete configuration for segment exporting,
including folder naming templates and g_reconverter options.
"""

import tkinter as tk
from tkinter import ttk
from typing import Dict, Any

from .gui_utils import center_window
from .config_frames import GReconverterOptionsFrame

class SegmentExportConfigWindow(tk.Toplevel):
    """A Toplevel window for managing all segment export parameters."""

    def __init__(self, master, controller, current_config: Dict[str, Any]):
        super().__init__(master)
        self.controller = controller
        self.config_data = current_config.copy()
        
        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("Configure Segment Export")
        self.geometry("800x750") 
        self.transient(self.master)

    def _init_vars(self):
        """Initializes all Tkinter variables for the parameters."""
        self.naming_vars = {
            "folder_name_template": tk.StringVar(),
        }
        self.g_reconverter_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):
        naming_config = self.config_data.get("naming_options", {})
        for key, var in self.naming_vars.items():
            var.set(naming_config.get(key, ''))

        g_reconverter_config = self.config_data.get("g_reconverter_options", {})
        for key, var in self.g_reconverter_vars.items():
            # --- MODIFICA: Fornisce un default del tipo corretto ---
            default_value = ''
            if isinstance(var, tk.BooleanVar):
                default_value = False
            elif isinstance(var, tk.IntVar):
                default_value = 0
            
            var.set(g_reconverter_config.get(key, default_value))

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

        naming_frame = ttk.LabelFrame(main_frame, text="Segment Folder Naming")
        naming_frame.pack(fill=tk.X, pady=(0, 15))
        naming_frame.columnconfigure(1, weight=1)
        ttk.Label(naming_frame, text="Folder Name Template:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        template_entry = ttk.Entry(naming_frame, textvariable=self.naming_vars["folder_name_template"])
        template_entry.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
        
        placeholders = "{Segment}, {StartBatch}, {EndBatch}, {BatchCount}"
        help_text = f"Available placeholders: {placeholders}"
        ttk.Label(naming_frame, text=help_text, wraplength=750, justify=tk.LEFT).grid(row=1, column=0, columnspan=2, sticky="w", padx=5, pady=(0, 5))

        g_reconverter_frame_container = ttk.LabelFrame(main_frame, text="g_reconverter Options for Export")
        g_reconverter_frame_container.pack(fill=tk.BOTH, expand=True)
        
        options_frame = GReconverterOptionsFrame(g_reconverter_frame_container, self.g_reconverter_vars)
        options_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(10, 0), side=tk.BOTTOM)
        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 _on_save(self):
        new_naming_config = {key: var.get() for key, var in self.naming_vars.items()}
        new_g_reconverter_config = {key: var.get() for key, var in self.g_reconverter_vars.items()}
        
        final_config = {
            "naming_options": new_naming_config,
            "g_reconverter_options": new_g_reconverter_config
        }
        
        self.controller.save_segment_export_config(final_config)
        self.destroy()

    def _on_cancel(self):
        self.destroy()