"""
DNS status widget for displaying DNS resolution status in the TUI.

This module provides a visual indicator widget that shows the current
DNS resolution status and allows users to toggle DNS service.
"""

from textual.widgets import Static
from textual.reactive import reactive
from textual.containers import Horizontal
from ..core.dns import DNSService


class DNSStatusWidget(Static):
    """
    Widget to display DNS resolution service status.
    
    Shows visual indicators for DNS service status and resolution progress.
    """

    # Reactive attributes
    dns_enabled: reactive[bool] = reactive(False)
    resolving_count: reactive[int] = reactive(0)
    resolved_count: reactive[int] = reactive(0)
    failed_count: reactive[int] = reactive(0)

    def __init__(self, dns_service: DNSService, **kwargs):
        super().__init__(**kwargs)
        self.dns_service = dns_service
        self.dns_enabled = dns_service.enabled
        self.update_status()

    def compose(self):
        """Create the DNS status display."""
        with Horizontal(classes="dns-status-container"):
            yield Static("", id="dns-status-indicator", classes="dns-indicator")
            yield Static("", id="dns-status-text", classes="dns-status-text")

    def update_status(self) -> None:
        """Update the DNS status display."""
        try:
            indicator = self.query_one("#dns-status-indicator", Static)
            text_widget = self.query_one("#dns-status-text", Static)

            if not self.dns_enabled:
                indicator.update("⭕")
                text_widget.update("DNS: Disabled")
                indicator.remove_class("dns-active")
                indicator.remove_class("dns-resolving")
                indicator.add_class("dns-disabled")
            elif self.resolving_count > 0:
                indicator.update("🔄")
                text_widget.update(f"DNS: Resolving ({self.resolving_count} pending)")
                indicator.remove_class("dns-disabled")
                indicator.remove_class("dns-active")
                indicator.add_class("dns-resolving")
            else:
                indicator.update("✅")
                status_parts = []
                if self.resolved_count > 0:
                    status_parts.append(f"{self.resolved_count} resolved")
                if self.failed_count > 0:
                    status_parts.append(f"{self.failed_count} failed")
                
                if status_parts:
                    status_text = f"DNS: Active ({', '.join(status_parts)})"
                else:
                    status_text = "DNS: Active"
                
                text_widget.update(status_text)
                indicator.remove_class("dns-disabled")
                indicator.remove_class("dns-resolving")
                indicator.add_class("dns-active")

        except Exception:
            # Widget not ready yet
            pass

    def watch_dns_enabled(self, enabled: bool) -> None:
        """React to DNS service enable/disable changes."""
        self.update_status()

    def watch_resolving_count(self, count: int) -> None:
        """React to changes in resolving count."""
        self.update_status()

    def watch_resolved_count(self, count: int) -> None:
        """React to changes in resolved count."""
        self.update_status()

    def watch_failed_count(self, count: int) -> None:
        """React to changes in failed count."""
        self.update_status()

    def update_from_service(self) -> None:
        """Update status from the current DNS service state."""
        self.dns_enabled = self.dns_service.enabled
        
        # Count DNS resolution states from the service
        if hasattr(self.dns_service, '_resolution_cache'):
            cache = self.dns_service._resolution_cache
            resolving = sum(1 for r in cache.values() if r.status == "RESOLVING")
            resolved = sum(1 for r in cache.values() if r.status in ["RESOLVED", "IP_MATCH"])
            failed = sum(1 for r in cache.values() if r.status in ["RESOLUTION_FAILED", "IP_MISMATCH"])
            
            self.resolving_count = resolving
            self.resolved_count = resolved
            self.failed_count = failed
        else:
            self.resolving_count = 0
            self.resolved_count = 0
            self.failed_count = 0

    def toggle_service(self) -> None:
        """Toggle the DNS service on/off."""
        if self.dns_service.enabled:
            self.dns_service.stop()
        else:
            self.dns_service.start()
        
        self.dns_enabled = self.dns_service.enabled
        self.update_status()

    def get_status_text(self) -> str:
        """Get current status as text for display purposes."""
        if not self.dns_enabled:
            return "DNS Disabled"
        elif self.resolving_count > 0:
            return f"DNS Resolving ({self.resolving_count})"
        else:
            parts = []
            if self.resolved_count > 0:
                parts.append(f"{self.resolved_count} resolved")
            if self.failed_count > 0:
                parts.append(f"{self.failed_count} failed")
            
            if parts:
                return f"DNS Active ({', '.join(parts)})"
            else:
                return "DNS Active"

    def get_status_symbol(self) -> str:
        """Get current status symbol."""
        if not self.dns_enabled:
            return "⭕"
        elif self.resolving_count > 0:
            return "🔄"
        else:
            return "✅"
