import os, sys

from PyQt6.QtWidgets import QVBoxLayout, QLabel, QDialog, QHBoxLayout
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QMovie


if getattr(sys, 'frozen', False):
    ASSETS_PATH = os.path.join(sys._MEIPASS, "assets")
else:
    ASSETS_PATH = os.path.join(os.path.dirname(__file__), "..", "assets")

class LoadingPopup(QDialog):
    """
    LoadingPopup is a class that represents a loading popup window.
    """

    close_signal = pyqtSignal() # Signal to close the loading popup

    def __init__(self, text: str = "Loading...", parent=None):
        super().__init__(parent)

        # << -- Signal setup -- >>
        self.close_signal.connect(self.close)

        # << -- Window setup -- >>
        self.setModal(True)
        self.setWindowTitle("Loading")
        self.setFixedSize(200, 200)

        # << -- Layouts setup -- >>
        self.main_layout = QVBoxLayout()
        self.text_layout = QHBoxLayout()
        self.gif_layout = QHBoxLayout()
        self.main_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.gif_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.text_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
    
        # << -- Loading gif label setup -- >>
        self.gif_movie = QMovie(os.path.join(ASSETS_PATH, "loading.gif"))
        self.gif_movie.setSpeed(200)
        self.gif_label = QLabel(self)
        self.gif_label.setMovie(self.gif_movie)
        self.gif_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.gif_label.setScaledContents(True)
        self.gif_label.setFixedSize(50, 50)

        # << -- Text label setup -- >>
        self.text_label = QLabel(text)
        self.text_label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # << -- Connect all components to the main layout -- >>
        self.gif_layout.addWidget(self.gif_label)
        self.text_layout.addWidget(self.text_label)
        self.main_layout.addLayout(self.gif_layout)
        self.main_layout.addLayout(self.text_layout)
        self.setLayout(self.main_layout)

    def show(self):
        """Show the loading popup."""
        self.gif_movie.start()
        super().show()

    def close(self):
        """Close the loading popup."""
        self.gif_movie.stop()
        super().close()
        


