# -*- coding: utf-8 -*-
"""Background service: archive playback badge overlay."""
from __future__ import annotations

import xbmc
import xbmcaddon

from lib import logger
from lib.archive_marker import clear_archive_playback
from lib.archive_overlay import ArchiveOverlay
from lib.constants import ADDON_ID

_addon = xbmcaddon.Addon(ADDON_ID)


class ArchivePlaybackPlayer(xbmc.Player):
    def __init__(self, overlay: ArchiveOverlay) -> None:
        super().__init__()
        self._overlay = overlay

    def onPlayBackStarted(self) -> None:
        self._overlay.on_playback_started(self)

    def onPlayBackStopped(self) -> None:
        self._overlay.hide()
        clear_archive_playback()

    def onPlayBackEnded(self) -> None:
        self.onPlayBackStopped()


class ArchivePlaybackMonitor(xbmc.Monitor):
    def __init__(self, overlay: ArchiveOverlay) -> None:
        super().__init__()
        self._overlay = overlay

    def onScreensaverActivated(self) -> None:
        self._overlay.hide()
        clear_archive_playback()

    def onSettingsChanged(self) -> None:
        self._overlay.on_settings_changed()


if __name__ == "__main__":
    overlay = ArchiveOverlay()
    player = ArchivePlaybackPlayer(overlay)
    monitor = ArchivePlaybackMonitor(overlay)
    logger.info("Archive overlay service started")
    while not monitor.abortRequested():
        try:
            overlay.tick(player)
        except Exception as exc:
            logger.error(f"Archive overlay tick failed: {exc}")
        if monitor.waitForAbort(0.4):
            break
    overlay.hide()
    clear_archive_playback()
    logger.info("Archive overlay service stopped")
