"""
Manages Docker container status checking for selected tools.
"""

from PySide6.QtGui import QIcon
from PySide6.QtCore import QSize, QTimer
from PySide6.QtWidgets import QWidget, QLabel

from src.controller.docker_controller import DockerController, refresh_mgr
from src.path_resolver import PathResolver


class ContainerStatusController(QWidget):
    def __init__(self, docker_status_label: QLabel, docker_status_icon: QLabel, parent=None) -> None:
        super().__init__(parent)
        self.docker_status_label = docker_status_label
        self.docker_status_icon = docker_status_icon
        self.timer = QTimer(self)
        self.init_docker_status_update()

    def init_docker_status_update(self) -> None:
        self.timer.timeout.connect(self.check_docker_status)
        refresh_mgr.cache_updated.connect(self.check_docker_status)
        self.timer.start(5000)
        self.check_docker_status()

    def check_docker_status(self) -> None:
        icon_size = QSize(24, 24)

        DockerController.refresh_cache()
        cache = DockerController._docker_check_cache

        if DockerController._working_icon is None:
            DockerController._working_icon = QIcon(PathResolver.resource_path('resources/assets/docker_working.png'))
        if DockerController._not_working_icon is None:
            DockerController._not_working_icon = QIcon(PathResolver.resource_path('resources/assets/docker_not_working.png'))

        if cache["docker_running"]:
            status_text = "Docker is running"
            icon = DockerController._working_icon
        else:
            status_text = "Docker is not running"
            icon = DockerController._not_working_icon

        if self.docker_status_label.text() != status_text:
            self.docker_status_label.setText(status_text)
            self.docker_status_icon.setPixmap(icon.pixmap(icon_size))
