"""Firewall — An/Aus (ufw/firewalld via Helper)."""
from __future__ import annotations

import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Adw, Gtk  # noqa: E402

from taninux.core import firewall
from taninux.gui.console import RunnerCard
from taninux.gui.process import ProcessRunner


def build() -> Gtk.Widget:
    page = Adw.PreferencesPage()
    group = Adw.PreferencesGroup(title="Firewall")
    page.add(group)

    if not firewall.installed():
        group.add(Adw.ActionRow(title="Install to turn on the firewall"))
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        box.set_margin_top(6)
        box.append(RunnerCard("Install", firewall.install_argv(), privileged=True))
        group.add(box)
        return page

    runner = ProcessRunner()
    status = Gtk.Label(xalign=0.0)
    status.add_css_class("dim-label")

    row = Adw.SwitchRow(
        title="Firewall",
        subtitle="Block unsolicited incoming connections",
    )
    row.set_active(firewall.enabled())

    def on_toggle(r, _p) -> None:
        runner.run(firewall.set_enabled_argv(r.get_active()), privileged=True)

    row.connect("notify::active", on_toggle)
    runner.connect("done", lambda _r, code: status.set_label(
        "✔ Updated" if code == 0 else f"✘ failed (exit {code})"))
    group.add(row)

    box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
    box.set_margin_top(6)
    box.append(status)
    group.add(box)
    return page
