# radar_data_reader/gui/export_config_window.py

"""
GUI Window for editing the configuration for segment exporting.
"""

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

from .gui_utils import center_window


class ExportConfigWindow(tk.Toplevel):
    """A Toplevel window for managing 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("Segment Export Configuration")
        self.geometry("600x400")
        self.transient(self.master)
        self.resizable(False, False)

    def _init_vars(self):
        """Initializes all Tkinter variables for the parameters."""
        self.vars = {
            "folder_name_template": tk.StringVar(),
            "export_video": tk.BooleanVar(),
            "export_gps_track": tk.BooleanVar(),
            "export_no_signal": 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, ""))

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

        # --- Folder Name Template Frame ---
        template_frame = ttk.LabelFrame(main_frame, text="Segment Folder Name Template")
        template_frame.pack(fill=tk.X, pady=(0, 10))
        template_frame.columnconfigure(0, weight=1)

        template_entry = ttk.Entry(
            template_frame, textvariable=self.vars["folder_name_template"]
        )
        template_entry.grid(row=0, column=0, sticky="ew", padx=5, pady=5)

        # Help text for placeholders
        placeholders = "{Segment}, {StartBatch}, {EndBatch}, {BatchCount}, {StartDate}, {StartTime}"
        help_text = f"Available placeholders: {placeholders}"
        ttk.Label(template_frame, text=help_text, wraplength=550, justify=tk.LEFT).grid(
            row=1, column=0, sticky="w", padx=5, pady=(0, 5)
        )

        # --- g_reconverter Options Frame ---
        options_frame = ttk.LabelFrame(
            main_frame, text="g_reconverter Options for Segment"
        )
        options_frame.pack(fill=tk.X, pady=10)

        ttk.Checkbutton(
            options_frame,
            text="Save Video (/vsave)",
            variable=self.vars["export_video"],
        ).pack(anchor="w", padx=5, pady=2)
        ttk.Checkbutton(
            options_frame,
            text="Save GPS Track (/gps)",
            variable=self.vars["export_gps_track"],
        ).pack(anchor="w", padx=5, pady=2)
        ttk.Checkbutton(
            options_frame,
            text="Export Metadata Only (no signal data, /nosign)",
            variable=self.vars["export_no_signal"],
        ).pack(anchor="w", padx=5, pady=2)

        # --- Action Buttons ---
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(20, 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_config = {key: var.get() for key, var in self.vars.items()}
        self.controller.save_export_config(new_config)
        self.destroy()

    def _on_cancel(self):
        self.destroy()
