"""
MSD Merge tab — Merge .msd files into a single MiniSEED.
"""

import logging
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox

from rshaketools.gui.helpers import labeled_entry, section_frame

logger = logging.getLogger("rshaketools")


class MsdMergeTab(ttk.Frame):
    def __init__(self, parent, app):
        super().__init__(parent)
        self.app = app
        self._build()

    def _build(self):
        frm = section_frame(self, "📦  Merge MSD Files")

        # Input directory
        ttk.Label(frm, text="Input directory:", font=("Helvetica", 10)).grid(
            row=0, column=0, sticky="w", padx=(0, 8), pady=3
        )
        self.input_dir = ttk.Entry(frm, width=36, font=("Menlo", 10))
        self.input_dir.grid(row=0, column=1, sticky="ew", pady=3)
        ttk.Button(frm, text="Browse …", command=self._browse_dir).grid(
            row=0, column=2, padx=(4, 0), sticky="w"
        )

        # Pattern
        self.pattern = labeled_entry(frm, "Glob pattern:", "*.msd", row=1)

        # Output
        ttk.Label(frm, text="Output file:", font=("Helvetica", 10)).grid(
            row=2, column=0, sticky="w", padx=(0, 8), pady=3
        )
        self.output_path = ttk.Entry(frm, width=36, font=("Menlo", 10))
        self.output_path.insert(0, "merged.mseed")
        self.output_path.grid(row=2, column=1, sticky="ew", pady=3)
        ttk.Button(frm, text="Browse …", command=self._browse_output).grid(
            row=2, column=2, padx=(4, 0), sticky="w"
        )

        # Merge button
        ttk.Button(frm, text="  🔗  Merge  ", command=self._do_merge).grid(
            row=3, column=0, columnspan=3, pady=(16, 4), sticky="e"
        )

    # ── Actions ─────────────────────────────────────────────────────────────
    def _browse_dir(self):
        path = filedialog.askdirectory()
        if path:
            self.input_dir.delete(0, tk.END)
            self.input_dir.insert(0, path)

    def _browse_output(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".mseed",
            filetypes=[("MiniSEED", "*.mseed"), ("All files", "*.*")],
        )
        if path:
            self.output_path.delete(0, tk.END)
            self.output_path.insert(0, path)

    def _do_merge(self):
        from rshaketools.msd import merge_msd_files

        input_dir = self.input_dir.get().strip()
        output_path = self.output_path.get().strip()
        pattern = self.pattern.get().strip() or "*.msd"

        if not input_dir:
            messagebox.showwarning("Validation", "Please select an input directory.")
            return
        if not output_path:
            messagebox.showwarning("Validation", "Please specify an output file.")
            return

        logger.info("Merging MSD files from %s …", input_dir)

        def _run():
            try:
                st = merge_msd_files(input_dir, output_path, pattern)
                logger.info("Merge complete — %d trace(s)", len(st))
                self.app.after(0, lambda: messagebox.showinfo(
                    "Merge Complete", f"Merged {len(st)} trace(s) → {output_path}"))
            except Exception as exc:
                logger.error("Merge failed: %s", exc)
                self.app.after(0, lambda: messagebox.showerror("Error", str(exc)))

        threading.Thread(target=_run, daemon=True).start()

    def apply_theme(self, c):
        pass
