import subprocess
import re
import time
from rich.console import Console
from rich.panel import Panel
from rich.live import Live


class NetworkMonitor:

    def __init__(self) -> None:
        self.console = Console()

    def __get_ping(self) -> float | None:
        result = subprocess.run(
            ["ping", "-c", "1", "8.8.8.8"],
            capture_output=True,
            text=True
        )

        match = re.search(r"time[=<](\d+\.?\d*)", result.stdout)
        if match:
            return float(match.group(1))
        return None

    def classify(self, ping):
        if ping is None:
            return ("NO CONNECTION", "red")
        if ping > 150:
            return ("POOR", "red")
        elif ping > 50:
            return ("GOOD", "yellow")
        else:
            return ("VERY GOOD", "green")
    
    def get_status_text(self):
        ping = self._NetworkMonitor__get_ping()
        status, color = self.classify(ping)
        ping_display = "N/A" if ping is None else f"{ping} ms"
        return f"[cyan]Ping:[/cyan] {ping_display} | [{color}]{status}[/{color}]"

    def build_ui(self):

        ping = self.__get_ping()
        status, color = self.classify(ping)

        ping_display = "N/A" if ping is None else f"{ping} ms"

        text = f"""
[bold cyan]Ping:[/bold cyan] {ping_display} >> [bold cyan]Quality:[/bold cyan] [{color}]{status}[/{color}]
"""

        return text

    