"""DNS summary widget."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.dom import NoMatches
from textual.widget import Widget
from textual.widgets import DataTable, Label

from flux_networking_shared.tui.models.network import ResolvedDnsServer


class DnsSummary(Widget):
    """Displays DNS servers in a DataTable."""

    BORDER_TITLE = "Name Servers"

    def __init__(
        self,
        links: dict[int, str] | None = None,
        servers: list[ResolvedDnsServer] | None = None,
    ) -> None:
        super().__init__()
        self.links = links or {}
        self.servers = servers or []

    def compose(self) -> ComposeResult:
        warning_label = Label(
            "No DNS Servers detected! This node will NOT be able to reach the internet",
            id="warning-label",
        )
        warning_label.display = False

        yield DataTable(cursor_type="none")
        yield warning_label

    def on_mount(self) -> None:
        self.update_table()

    def update_table(self) -> None:
        """Update the DataTable with current servers."""
        if not self.servers:
            return

        try:
            table = self.query_one(DataTable)
        except NoMatches:
            return

        table.clear(columns=True)

        table.add_column("Address", width=15)
        table.add_column("Interface Name", width=20)
        table.add_column("Family", width=8)

        rows = [x.data_row for x in self.servers]
        table.add_rows(rows)

    def update_servers(
        self, links: dict[int, str], servers: list[ResolvedDnsServer]
    ) -> None:
        """Update servers and refresh display."""
        self.links = links
        self.servers = servers

        if self.is_mounted:
            self.update_table()
            # Show warning if no servers
            try:
                warning = self.query_one("#warning-label", Label)
                warning.display = len(servers) == 0
            except NoMatches:
                pass
