"""Native desktop control panel. Tkinter is bundled with standard Windows Python."""
import asyncio
import queue
import threading
import tkinter as tk
from pathlib import Path
from tkinter import ttk, filedialog
from tkinter.scrolledtext import ScrolledText

from server import Simulator
from pairing import PairingDialog
from tls_support import DEFAULT_CERT, DEFAULT_KEY, certificate_fingerprint, create_certificate, new_token, server_context

TLS_MODE = "TLS · Encrypted"
TCP_MODE = "TCP · Unencrypted"


class App:
    def __init__(self, root):
        self.root = root
        self.loop = asyncio.new_event_loop()
        self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
        self.thread.start()
        self.events = queue.Queue(maxsize=1000)
        self.sim = None
        self.busy = False
        root.title("MangoLink Simulator 0.3.0 — Mango Juice Tech")
        root.geometry("960x800")
        root.minsize(780, 700)
        style = ttk.Style()
        style.theme_use("clam")
        style.configure("TButton", padding=8)
        style.configure("Title.TLabel", font=("Segoe UI", 22, "bold"), foreground="#bf5700")
        body = ttk.Frame(root, padding=20)
        body.pack(fill="both", expand=True)
        ttk.Label(body, text="MangoLink Simulator", style="Title.TLabel").pack(anchor="w")
        ttk.Label(body, text="A virtual embedded device for logs, telemetry and commands.").pack(anchor="w", pady=(4, 16))
        row = ttk.Frame(body)
        row.pack(fill="x")
        self.host = tk.StringVar(value="0.0.0.0")
        self.port = tk.StringVar(value="8766")
        self.token = tk.StringVar(value=new_token())
        self.inputs = []
        for label, var, width in [("Bind address", self.host, 16), ("Port", self.port, 7), ("Session token", self.token, 22)]:
            cell = ttk.Frame(row)
            cell.pack(side="left", padx=(0, 12))
            ttk.Label(cell, text=label).pack(anchor="w")
            entry = ttk.Entry(cell, textvariable=var, width=width)
            entry.pack()
            self.inputs.append(entry)
        mode_row = ttk.Frame(body)
        mode_row.pack(fill="x", pady=(12, 8))
        ttk.Label(mode_row, text="Connection mode").pack(side="left", padx=(0, 12))
        self.mode = tk.StringVar(value=TLS_MODE)
        self.mode_combo = ttk.Combobox(mode_row, textvariable=self.mode, values=[TLS_MODE, TCP_MODE], state="readonly", width=24)
        self.mode_combo.pack(side="left")
        self.mode_combo.bind("<<ComboboxSelected>>", lambda _: self.mode_changed())
        self.cert = tk.StringVar(value=str(DEFAULT_CERT))
        self.key = tk.StringVar(value=str(DEFAULT_KEY))
        self.file_buttons = []
        for label, variable in [("TLS certificate", self.cert), ("Private key", self.key)]:
            row = ttk.Frame(body)
            row.pack(fill="x", pady=3)
            ttk.Label(row, text=label, width=16).pack(side="left")
            entry = ttk.Entry(row, textvariable=variable)
            entry.pack(side="left", fill="x", expand=True, padx=(0, 8))
            self.inputs.append(entry)
            button = ttk.Button(row, text="Browse…", command=lambda v=variable: self.browse_file(v))
            button.pack(side="right")
            self.file_buttons.append(button)
        cert_actions = ttk.Frame(body)
        cert_actions.pack(fill="x", pady=6)
        self.create_button = ttk.Button(cert_actions, text="Create TLS certificate", command=self.generate_certificate)
        self.create_button.pack(side="left", padx=(0, 12))
        folder_button = ttk.Button(cert_actions, text="Choose certificate folder…", command=self.choose_certificate_folder)
        folder_button.pack(side="left")
        self.file_buttons.append(folder_button)
        ttk.Label(body, text="Certificate SHA-256 — copy into MangoLink:").pack(anchor="w")
        self.fingerprint = tk.StringVar()
        ttk.Entry(body, textvariable=self.fingerprint, state="readonly", font=("Consolas", 10)).pack(fill="x")
        self.mode_notice = tk.StringVar()
        ttk.Label(body, textvariable=self.mode_notice, foreground="#a33c00", wraplength=880).pack(anchor="w", pady=(8, 0))
        self.refresh_fingerprint()
        self.mode_changed()
        self.status = tk.StringVar(value="Stopped")
        ttk.Label(body, textvariable=self.status).pack(anchor="w", pady=12)
        buttons = ttk.Frame(body)
        buttons.pack(fill="x")
        self.start_button = ttk.Button(buttons, text="Start server", command=self.start)
        self.start_button.pack(side="left", padx=(0, 8))
        self.stop_button = ttk.Button(buttons, text="Stop server", command=self.stop, state="disabled")
        self.stop_button.pack(side="left", padx=(0, 8))
        self.pair_button = ttk.Button(buttons, text="Show pairing QR…", command=self.show_pairing, state="disabled")
        self.pair_button.pack(side="left")
        self.actions = []
        action_grid = ttk.Frame(body)
        action_grid.pack(fill="x", pady=(8, 0))
        action_grid.columnconfigure((0, 1), weight=1)
        for index, (label, factory) in enumerate([("Inject warning", lambda: self.sim.log("WARN", "Desktop warning event")),
                               ("Inject error", lambda: self.sim.log("ERROR", "Desktop error event")),
                               ("Drop clients", lambda: self.sim.disconnect_all()),
                               ("Simulate reboot", lambda: self.sim.reboot())]):
            button = ttk.Button(action_grid, text=label, command=lambda f=factory: self.action(f), state="disabled")
            button.grid(row=index // 2, column=index % 2, sticky="ew", padx=(0, 8), pady=(0, 6))
            self.actions.append(button)
        self.console = ScrolledText(body, height=8, bg="#152019", fg="#e4f0e8", font=("Consolas", 10), state="disabled")
        self.console.pack(fill="both", expand=True, pady=12)
        ttk.Label(body, text="Phone: use this PC's LAN IP, port and token. 0.0.0.0 is a bind address, not the phone's destination.", wraplength=740).pack(anchor="w")
        ttk.Label(body, text="Keep the private key on this PC. Share only the certificate fingerprint. TLS failures never fall back to TCP.", wraplength=880).pack(anchor="w", pady=(8, 0))
        root.protocol("WM_DELETE_WINDOW", self.close)
        self.poll_id = root.after(100, self.poll)

    def show_pairing(self):
        if self.busy or not self.sim or self.sim.mode != "TLS":
            return
        PairingDialog(self.root, self.host.get().strip(), self.sim.port,
                      self.serving_fingerprint, self.sim.token)

    def mode_changed(self):
        tls = self.mode.get() == TLS_MODE
        if self.port.get() in ("8765", "8766"):
            self.port.set("8766" if tls else "8765")
        self.mode_notice.set("TLS encrypts traffic. Verify the displayed fingerprint on the phone before connecting."
                             if tls else "UNENCRYPTED TCP: token, commands and logs are readable on the network. Trusted lab LAN only.")

    def refresh_fingerprint(self):
        try:
            self.fingerprint.set(certificate_fingerprint(self.cert.get()))
        except Exception:
            self.fingerprint.set("Create or choose a certificate for TLS.")

    def browse_file(self, variable):
        if self.sim or self.busy:
            return
        path = filedialog.askopenfilename(title="Choose TLS file")
        if path:
            variable.set(path)
            self.refresh_fingerprint()

    def choose_certificate_folder(self):
        if self.sim or self.busy:
            return
        folder = filedialog.askdirectory(title="Choose a writable TLS certificate folder")
        if folder:
            directory = Path(folder).expanduser().resolve()
            self.cert.set(str(directory / "server-cert.pem"))
            self.key.set(str(directory / "server-key.pem"))
            self.refresh_fingerprint()

    def generate_certificate(self):
        if self.sim or self.busy:
            return
        try:
            cert, key = create_certificate(Path(self.cert.get()).parent)
            self.cert.set(str(cert))
            self.key.set(str(key))
            self.refresh_fingerprint()
            self.emit("Created a new TLS identity. Keep the private key on the PC; pair the displayed fingerprint on your phone.")
        except Exception as exc:
            self.emit(str(exc))

    def emit(self, message):
        try:
            self.events.put_nowait(("log", message))
        except queue.Full:
            pass

    def submit(self, coro, event):
        future = asyncio.run_coroutine_threadsafe(coro, self.loop)
        def done(f):
            try:
                f.result()
                self.events.put((event, None))
            except Exception as exc:
                self.events.put(("failure", str(exc)))
        future.add_done_callback(done)

    def start(self):
        if self.busy or self.sim:
            return
        try:
            port = int(self.port.get())
            if not 1 <= port <= 65535:
                raise ValueError("Port must be 1..65535")
            tls = self.mode.get() == TLS_MODE
            context = server_context(self.cert.get(), self.key.get()) if tls else None
            self.serving_fingerprint = certificate_fingerprint(self.cert.get()) if tls else ""
            self.refresh_fingerprint()
            self.sim = Simulator(token=self.token.get(), event=self.emit)
            self.busy = True
            self.start_button.config(state="disabled")
            self.mode_combo.config(state="disabled")
            self.create_button.config(state="disabled")
            for widget in self.inputs:
                widget.config(state="readonly")
            for button in self.file_buttons:
                button.config(state="disabled")
            self.submit(self.sim.start(self.host.get().strip(), port, ssl_context=context), "started")
        except (ValueError, OSError, RuntimeError) as exc:
            self.sim = None
            self.emit(str(exc))

    def stop(self):
        if self.sim and not self.busy:
            self.busy = True
            self.stop_button.config(state="disabled")
            self.pair_button.config(state="disabled")
            for b in self.actions:
                b.config(state="disabled")
            self.submit(self.sim.stop(), "stopped")

    def action(self, factory):
        if self.sim and not self.busy:
            self.submit(factory(), "action")

    def poll(self):
        for _ in range(200):
            try:
                kind, message = self.events.get_nowait()
            except queue.Empty:
                break
            if kind == "started":
                self.busy = False
                self.status.set(f"Listening on {self.host.get()}:{self.port.get()} · {self.mode.get()}")
                self.stop_button.config(state="normal")
                self.pair_button.config(state="normal" if self.sim.mode == "TLS" else "disabled")
                self.mode_combo.config(state="disabled")
                self.create_button.config(state="disabled")
                for button in self.file_buttons:
                    button.config(state="disabled")
                for widget in self.inputs:
                    widget.config(state="readonly")
                for b in self.actions:
                    b.config(state="normal")
            elif kind in ("stopped", "failure"):
                if kind == "failure":
                    self.emit(message)
                    if self.sim:
                        asyncio.run_coroutine_threadsafe(self.sim.stop(), self.loop)
                self.busy = False
                self.sim = None
                self.status.set("Stopped")
                self.start_button.config(state="normal")
                self.mode_combo.config(state="readonly")
                self.create_button.config(state="normal")
                for button in self.file_buttons:
                    button.config(state="normal")
                self.stop_button.config(state="disabled")
                self.pair_button.config(state="disabled")
                for widget in self.inputs:
                    widget.config(state="normal")
                for b in self.actions:
                    b.config(state="disabled")
            elif kind == "log":
                self.console.config(state="normal")
                self.console.insert("end", message + "\n")
                if int(self.console.index("end-1c").split(".")[0]) > 1000:
                    self.console.delete("1.0", "101.0")
                self.console.see("end")
                self.console.config(state="disabled")
        self.poll_id = self.root.after(100, self.poll)

    def close(self):
        self.root.after_cancel(self.poll_id)
        async def shutdown():
            if self.sim:
                await self.sim.stop()
        try:
            asyncio.run_coroutine_threadsafe(shutdown(), self.loop).result(timeout=3)
        except Exception:
            pass
        self.loop.call_soon_threadsafe(self.loop.stop)
        self.thread.join(timeout=1)
        if not self.thread.is_alive():
            self.loop.close()
        self.root.destroy()


if __name__ == "__main__":
    root = tk.Tk()
    App(root)
    root.mainloop()
