''' app/ui/widgets/statusbar.py '''
import os.path
import socket
import threading
import time

from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QStatusBar, QLabel

from src.api.server_proxy import RenderServerProxy
from src.engines.engine_manager import EngineManager
from src.utilities.misc_helper import resources_dir


class StatusBar(QStatusBar):
    """
    Initialize the status bar.

    Args:
        parent: The parent widget.
    """

    def __init__(self, parent) -> None:
        super().__init__(parent)

        def background_update():

            proxy = RenderServerProxy(socket.gethostname())
            proxy.start_background_update()
            image_names = {'Ready': 'GreenCircle.png', 'Offline': "RedSquare.png"}

            # Check for status change every 1s on background thread
            while True:
                try:
                    # update status label - get download status
                    new_status = proxy.status()
                    active_downloads = EngineManager.active_downloads()
                    if active_downloads:
                        if len(active_downloads) == 1:
                            task = active_downloads[0]
                            new_status = f"{new_status} | Downloading {task.engine.capitalize()} {task.version}..."
                        else:
                            new_status = f"{new_status} | Downloading {len(active_downloads)} engines"
                    self.messageLabel.setText(new_status)

                    # update status image
                    new_image_name = image_names.get(new_status, 'Synchronize.png')
                    new_image_path = os.path.join(resources_dir(), new_image_name)
                    self.label.setPixmap((QPixmap(new_image_path).scaled(16, 16, Qt.AspectRatioMode.KeepAspectRatio)))
                except RuntimeError:  # ignore runtime errors during shutdown
                    pass
                time.sleep(1)

        background_thread = threading.Thread(target=background_update,)
        background_thread.daemon = True
        background_thread.start()

        # Create a label that holds an image
        self.label = QLabel()
        image_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'resources',
                                  'RedSquare.png')
        pixmap = (QPixmap(image_path).scaled(16, 16, Qt.AspectRatioMode.KeepAspectRatio))
        self.label.setPixmap(pixmap)
        self.addWidget(self.label)

        # Create a label for the message
        self.messageLabel = QLabel()
        self.addWidget(self.messageLabel)

        # Call this method to display a message
        self.messageLabel.setText("Loading...")
