#!/usr/bin/python3


from __future__ import annotations

import logging
import time
from multiprocessing import Process
from typing import Optional

from slpkg.config import config_load
from slpkg.progress_bar import ProgressBar
from slpkg.views.package_line import Imprint

logger = logging.getLogger(__name__)


class ViewProcess:
    """View the process messages."""

    def __init__(self) -> None:
        logger.debug("Initializing ViewProcess module.")
        self.red = config_load.red
        self.endc = config_load.endc

        self.progress = ProgressBar()
        self.imp = Imprint()

        self.bar_process: Optional[Process] = None
        logger.debug("ViewProcess module initialized.")

    def message(self, message: str) -> None:
        """Show spinner with message.

        Args:
            message (str): Message of spinner.
        """
        logger.info("Displaying progress message: '%s'", message)
        self._stop_bar()  # Stop any previously running bar before starting a new one.
        self.bar_process = Process(target=self.progress.progress_bar, args=(message,))
        self.bar_process.start()
        logger.debug("Progress bar process started for message: '%s' (PID: %s)", message, self.bar_process.pid)

    def _stop_bar(self) -> None:
        """Terminate and join the progress bar process if it is running."""
        time.sleep(0.1)  # Small delay to ensure visual update.
        if self.bar_process is not None:
            if self.bar_process.is_alive():
                self.bar_process.terminate()
                self.bar_process.join()
                logger.debug("Progress bar process terminated and joined.")
            else:
                logger.debug("Progress bar process was already not alive.")
        else:
            logger.debug("No active progress bar process to stop.")

    def done(self) -> None:
        """Show done message."""
        logger.info("Progress bar process indicating 'Done'.")
        self._stop_bar()
        print(f"\b{self.imp.done}", end="")
        print("\x1b[?25h")  # Reset cursor after hiding.
        logger.info("'Done' message displayed and cursor reset.")

    def failed(self) -> None:
        """Show failed message."""
        logger.warning("Progress bar process indicating 'Failed'.")
        self._stop_bar()
        print(f"\b{self.red}{self.imp.failed}{self.endc}", end="")
        print("\x1b[?25h")  # Reset cursor after hiding.
        logger.warning("'Failed' message displayed and cursor reset.")
