# interface/ui.py

import logging
from rich.console import Console
from rich.table import Table
from rich.progress import (
    Progress,
    SpinnerColumn,
    BarColumn,
    TextColumn,
    TimeRemainingColumn,
)
from rcdl.core.models import VideoStatus


class UI:
    console = Console()
    logger = logging.getLogger()

    @staticmethod
    def _log_to_file(log_level, msg: str):
        log_level(msg)

    @classmethod
    def info(cls, msg: str):
        """Print text to console and to log.info"""
        cls.console.print(msg)
        cls._log_to_file(cls.logger.info, msg)

    @classmethod
    def debug(cls, msg: str):
        cls.console.print(f"[dim]{msg}[/]")
        cls._log_to_file(cls.logger.debug, msg)

    @classmethod
    def warning(cls, msg: str):
        cls.console.print(f"[yellow]{msg}[/]")
        cls._log_to_file(cls.logger.debug, msg)

    @classmethod
    def error(cls, msg: str):
        cls.console.print(f"[red]{msg}[/]")
        cls._log_to_file(cls.logger.debug, msg)

    @classmethod
    def db_videos_status_table(cls, info: dict):
        """
        Print to cli a table with info of numbers of videos per status.
        Take in arg a dict: {
            "not_downloaded": int,
            "downloaded": int, "failed: int", "skipped: int", "ignored: int"}
        """

        table = Table(title="DB Videos status")

        table.add_column("Video status")
        table.add_column("Number of videos")

        for status in VideoStatus:
            name = status.value.replace("_", " ").capitalize()
            table.add_row(name, str(info[status.value]))

        cls.console.print(table)

    @classmethod
    def progress_posts_fetcher(cls, max_pages: int):
        progress = Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            BarColumn(),
            console=cls.console,
            transient=True,  # remove progress bar after finish
        )
        return progress

    @classmethod
    def video_progress(cls, total: int):
        progress = Progress(
            SpinnerColumn(),
            TextColumn("[bold cyan]{task.description}"),
            BarColumn(),
            TextColumn("{task.completed}/{task.total}"),
            TimeRemainingColumn(),
            console=cls.console,
            transient=True,  # remove the bar after completion
        )
        return progress

    @classmethod
    def update_video_progress(cls, progress, task_id, creator_id, filename):
        desc = f"[cyan]{creator_id}[/] -> [green]{filename}[/]"
        progress.update(task_id, advance=1, description=desc)
