from __future__ import annotations

import csv
import tkinter as tk
from tkinter import filedialog, messagebox, ttk

from gui.adapters import filter_rows, format_timestamp, metadata_summary
from gui.widgets import DataTable, Page


class EventsPage(Page):
    def __init__(self, parent):
        super().__init__(parent, "Events", "Recent normalized telemetry from EventDatabase")
        controls = ttk.Frame(self); controls.grid(row=2, column=0, sticky="ew", pady=(0, 10))
        self.search = tk.StringVar(); self.event = tk.StringVar(value="All"); self.severity = tk.StringVar(value="All")
        ttk.Entry(controls, textvariable=self.search, width=30).pack(side="left")
        self.event_box = ttk.Combobox(controls, textvariable=self.event, values=["All"], state="readonly", width=18); self.event_box.pack(side="left", padx=8)
        ttk.Combobox(controls, textvariable=self.severity, values=["All", "info", "low", "medium", "high", "critical"], state="readonly", width=12).pack(side="left")
        ttk.Button(controls, text="Apply", command=self._render).pack(side="left", padx=8)
        ttk.Button(controls, text="Export recent CSV", command=self.export).pack(side="right")
        self.table = DataTable(self, [("timestamp", "Timestamp", 150), ("event_type", "Event", 130), ("pid", "PID", 65),
                                      ("process_name", "Process", 140), ("severity", "Severity", 80), ("source", "Source", 110),
                                      ("rule_id", "Rule", 90), ("metadata", "Metadata summary", 240)])
        self.table.grid(row=3, column=0, sticky="nsew"); self.rowconfigure(3, weight=1); self.rows = []

    def refresh(self, snapshot):
        self.rows = [{**item, "timestamp": format_timestamp(item.get("timestamp")), "metadata": metadata_summary(item.get("metadata"))} for item in snapshot["events"]]
        self.event_box.configure(values=["All"] + sorted({str(x.get("event_type")) for x in self.rows if x.get("event_type")})); self._render()

    def _render(self): self.table.set_rows(filter_rows(self.rows, self.search.get(), event_type=self.event.get(), severity=self.severity.get()))

    def export(self):
        path = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV", "*.csv")])
        if not path: return
        rows = filter_rows(self.rows, self.search.get(), event_type=self.event.get(), severity=self.severity.get())
        with open(path, "w", newline="", encoding="utf-8") as stream:
            writer = csv.DictWriter(stream, fieldnames=self.table.columns, extrasaction="ignore"); writer.writeheader(); writer.writerows(rows)
        messagebox.showinfo("Export complete", f"Exported {len(rows)} events.")

