"""Digitalclock module for widgets."""

from __future__ import annotations

import random
from datetime import datetime, timedelta, timezone

from PySide2.QtCore import Qt, QTimer
from PySide2.QtGui import QResizeEvent
from PySide2.QtWidgets import QLabel, QWidget
from pytola_core import logger

from ..config import conf


class DigitalClock(QLabel):
    """数字时钟显示组件."""

    def __init__(self, parent: QWidget | None = None) -> None:
        super().__init__(parent)
        self.resize(*conf.CLOCK_SIZE)

        self.setAlignment(Qt.AlignCenter)
        self._color = conf.DIGITAL_BORDER_COLORS[0]

        # 初始化时立即设置样式和当前时间，避免显示 00:00:00
        current = datetime.now(timezone.utc) + timedelta(hours=8)
        self.setStyleSheet(
            f"font: {conf.DIGITAL_FONT}; color: white; background-color: black; "
            f"border: 2px dashed {self._color}; border-radius: 10px; padding: 10px;",
        )
        self.setText(current.strftime(conf.DIGITAL_TIMER_FORMAT))

        # 初始化定时器
        self._timer = QTimer()
        self._timer.timeout.connect(self.update_time)
        # 启动定时器
        self._timer.start(conf.DIGITAL_UPDATE_INTERVAL)

    def update_time(self) -> None:
        """更新当前时间显示并添加闪烁效果."""
        current = datetime.now(timezone.utc) + timedelta(hours=8)

        # 先更新颜色
        self._color = random.choice([c for c in conf.DIGITAL_BORDER_COLORS if c != self._color])  # noqa: S311

        # 先设置样式，再设置文本，确保样式立即生效
        self.setStyleSheet(
            f"font: {conf.DIGITAL_FONT}; color: white; background-color: black; "
            f"border: 2px dashed {self._color}; border-radius: 10px; padding: 10px;",
        )

        # 最后设置文本内容
        self.setText(current.strftime(conf.DIGITAL_TIMER_FORMAT))

    def resizeEvent(self, event: QResizeEvent) -> None:
        """处理窗口 resize 事件."""
        super().resizeEvent(event)

        conf.CLOCK_SIZE = [self.width(), self.height()]
        logger.info(f"CLOCK_SIZE updated: {conf.CLOCK_SIZE}")
