#!/usr/bin/env python3
"""Splash overlay shown while scanning the music library for the first time."""

from PyQt6.QtWidgets import QDialog, QVBoxLayout, QLabel, QWidget, QApplication
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QPainter, QPen, QColor, QFont


class _Spinner(QWidget):
    """A spinning arc — like a circular progress indicator."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(64, 64)
        self._angle = 0.0
        self._timer = QTimer(self)
        self._timer.timeout.connect(self._tick)
        self._timer.start(30)

    def _tick(self):
        self._angle = (self._angle + 6) % 360
        self.update()

    def paintEvent(self, event):
        p = QPainter(self)
        p.setRenderHint(QPainter.RenderHint.Antialiasing)
        r = self.rect().adjusted(4, 4, -4, -4)

        p.setPen(QPen(QColor("#e0e0e0"), 3, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
        p.drawEllipse(r)

        p.setPen(QPen(QColor("#3b82f6"), 4, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
        p.drawArc(r, int(self._angle * 16), 60 * 16)


class SplashOverlay(QDialog):
    """Modal overlay with a spinning animation + progress counter.

    Usage::

        splash = SplashOverlay(window)
        splash.show()
        # … scan …
        splash.set_progress(current, total)
        splash.close()
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog
        )
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
        self.setModal(True)

        self._card = QWidget(self)
        self._card.setObjectName("card")
        self._card.setFixedSize(340, 240)

        layout = QVBoxLayout(self._card)
        layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.setSpacing(16)

        self._spinner = _Spinner()
        layout.addWidget(self._spinner, alignment=Qt.AlignmentFlag.AlignCenter)

        self._title = QLabel("Создаём музыкальную\nмедиатеку…")
        self._title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        f = self._title.font()
        f.setPointSize(16)
        f.setBold(True)
        self._title.setFont(f)
        layout.addWidget(self._title)

        self._count = QLabel("")
        self._count.setAlignment(Qt.AlignmentFlag.AlignCenter)
        f2 = self._count.font()
        f2.setPointSize(12)
        self._count.setFont(f2)
        layout.addWidget(self._count)

        self._card.setStyleSheet("""
            #card {
                background: white;
                border-radius: 16px;
            }
            QLabel {
                color: #333;
                background: transparent;
            }
        """)

    def _recenter(self):
        if not self.parent():
            return
        pr = self.parent().rect()
        self.setGeometry(pr)
        cx = (pr.width() - self._card.width()) // 2
        cy = (pr.height() - self._card.height()) // 2
        self._card.move(cx, cy)

    def showEvent(self, event):
        self._recenter()
        super().showEvent(event)
        QApplication.processEvents()

    def resizeEvent(self, event):
        self._recenter()
        super().resizeEvent(event)

    def set_progress(self, current: int, total: int) -> None:
        """Update the file counter shown on the overlay."""
        if total > 0:
            self._count.setText(f"Файл {current} из {total}")
        else:
            self._count.setText(f"Файл {current}")
        QApplication.processEvents()
