"""
Acquisition tab — SSH datetime sync & waveform download.
"""

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 AcquisitionTab(ttk.Frame):
    def __init__(self, parent, app):
        super().__init__(parent)
        self.app = app
        self._build()

    # ── Build ───────────────────────────────────────────────────────────────
    def _build(self):
        canvas = tk.Canvas(self, highlightthickness=0)
        scrollbar = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
        self.inner = ttk.Frame(canvas)
        self.inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.create_window((0, 0), window=self.inner, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        # ── Sync DateTime ───────────────────────────────────────────────────
        frm_sync = section_frame(self.inner, "🔄  Sync DateTime")

        self.sync_host = labeled_entry(frm_sync, "Host:", "rs.local", row=0)
        self.sync_user = labeled_entry(frm_sync, "Username:", "myshake", row=1)
        self.sync_pass = labeled_entry(frm_sync, "Password:", "shakeme", row=2, show="*")

        btn_sync = ttk.Button(frm_sync, text="  ⚡  Sync Now  ", command=self._do_sync)
        btn_sync.grid(row=3, column=0, columnspan=2, pady=(12, 4), sticky="e")

        # ── Download Waveform ───────────────────────────────────────────────
        frm_dl = section_frame(self.inner, "📥  Download Waveform")

        self.dl_host = labeled_entry(frm_dl, "Host:", "rs.local", row=0)
        self.dl_port = labeled_entry(frm_dl, "Port:", "16032", row=1)
        self.dl_net = labeled_entry(frm_dl, "Network:", "AM", row=2)
        self.dl_sta = labeled_entry(frm_dl, "Station:", "RCA8F", row=3)
        self.dl_loc = labeled_entry(frm_dl, "Location:", "00", row=4)
        self.dl_cha = labeled_entry(frm_dl, "Channel:", "EH*", row=5)
        self.dl_start = labeled_entry(frm_dl, "Start (UTC):", "2023-01-11T08:10:00", row=6)
        self.dl_end = labeled_entry(frm_dl, "End (UTC):", "2023-01-11T08:40:00", row=7)
        self.dl_output = labeled_entry(frm_dl, "Output file:", "output.mseed", row=8)

        btn_browse = ttk.Button(frm_dl, text="Browse …", command=self._browse_output)
        btn_browse.grid(row=8, column=2, padx=(4, 0), sticky="w")

        btn_avail = ttk.Button(frm_dl, text="  🔍  Check Availability  ", command=self._do_check)
        btn_avail.grid(row=9, column=0, pady=(12, 4), sticky="w")

        btn_dl = ttk.Button(frm_dl, text="  📥  Download  ", command=self._do_download)
        btn_dl.grid(row=9, column=1, pady=(12, 4), sticky="e")

    # ── Actions ─────────────────────────────────────────────────────────────
    def _do_sync(self):
        from rshaketools.acquisition import sync_datetime
        host = self.sync_host.get().strip()
        user = self.sync_user.get().strip()
        pwd = self.sync_pass.get().strip()
        if not all([host, user, pwd]):
            messagebox.showwarning("Validation", "Please fill in all Sync fields.")
            return
        logger.info("Starting datetime sync …")

        def _run():
            try:
                result = sync_datetime(host, user, pwd)
                logger.info("Sync complete: %s", result)
                self.app.after(0, lambda: messagebox.showinfo("Sync Complete", result or "Success"))
            except Exception as exc:
                logger.error("Sync failed: %s", exc)
                self.app.after(0, lambda: messagebox.showerror("Sync Error", str(exc)))

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

    def _do_check(self):
        from rshaketools.acquisition import check_availability
        host = self.dl_host.get().strip()
        port = int(self.dl_port.get().strip())
        net = self.dl_net.get().strip()
        sta = self.dl_sta.get().strip()
        cha = self.dl_cha.get().strip()
        logger.info("Checking availability …")

        def _run():
            try:
                result = check_availability(host, port, net, sta, cha)
                logger.info("Availability: %s", result)
                self.app.after(0, lambda: messagebox.showinfo("Availability", str(result)))
            except Exception as exc:
                logger.error("Check failed: %s", exc)
                self.app.after(0, lambda: messagebox.showerror("Error", str(exc)))

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

    def _do_download(self):
        from rshaketools.acquisition import download_waveforms
        kwargs = {
            "host": self.dl_host.get().strip(),
            "port": int(self.dl_port.get().strip()),
            "network": self.dl_net.get().strip(),
            "station": self.dl_sta.get().strip(),
            "location": self.dl_loc.get().strip(),
            "channel": self.dl_cha.get().strip(),
            "starttime": self.dl_start.get().strip(),
            "endtime": self.dl_end.get().strip(),
            "output_path": self.dl_output.get().strip(),
        }
        if not kwargs["starttime"] or not kwargs["endtime"]:
            messagebox.showwarning("Validation", "Please provide start & end times.")
            return
        logger.info("Starting waveform download …")

        def _run():
            try:
                st = download_waveforms(**kwargs)
                logger.info("Download complete — %d trace(s)", len(st))
                self.app.after(0, lambda: messagebox.showinfo(
                    "Download Complete", f"Saved {len(st)} trace(s) to {kwargs['output_path']}"))
            except Exception as exc:
                logger.error("Download failed: %s", exc)
                self.app.after(0, lambda: messagebox.showerror("Error", str(exc)))

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

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

    # ── Theme ───────────────────────────────────────────────────────────────
    def apply_theme(self, c):
        pass  # ttk styling handled globally
