"""Show an entry.

.. include:: ../man/cobib-show.1.html_fragment
"""

from __future__ import annotations

import argparse
import logging

from rich.console import ConsoleRenderable
from rich.syntax import Syntax
from typing_extensions import override

from cobib.config import Event, config
from cobib.database import Database
from cobib.parsers.bibtex import BibtexParser

from .base_command import Command

LOGGER = logging.getLogger(__name__)
"""@private module logger."""


class ShowCommand(Command):
    """The Show Command.

    This command can parse the following arguments:

        * `label`: the label of the entry to be shown.
    """

    name = "show"

    @override
    def __init__(self, *args: str) -> None:
        super().__init__(*args)

        self.entry_str: str = ""
        """The string-formatted `cobib.database.Entry` shown by this command."""

    @override
    @classmethod
    def init_argparser(cls) -> None:
        parser = argparse.ArgumentParser(
            prog="show",
            description="Show subcommand parser.",
            epilog="Read cobib-show.1 for more help.",
        )
        parser.add_argument("label", type=str, help="label of the entry")
        cls.argparser = parser

    @override
    def execute(self) -> None:
        LOGGER.debug("Starting Show command.")

        Event.PreShowCommand.fire(self)

        try:
            entry = Database()[self.largs.label]
            entry_str = BibtexParser(encode_latex=config.commands.show.encode_latex).dump(entry)

            self.entry_str = entry_str
        except KeyError:
            msg = f"No entry with the label '{self.largs.label}' could be found."
            LOGGER.error(msg)

        Event.PostShowCommand.fire(self)

    @override
    def render_porcelain(self) -> list[str]:
        return self.entry_str.split("\n")

    @override
    def render_rich(self) -> ConsoleRenderable:
        syntax = Syntax(
            self.entry_str,
            "bibtex",
            theme=config.theme.syntax.get_theme(),
            background_color=config.theme.syntax.get_background_color(),
            line_numbers=config.theme.syntax.line_numbers,
            word_wrap=True,
        )
        return syntax
