# -*- 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(destroy=True, reset_fullscreen=True)
        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(destroy=True, reset_fullscreen=True)
        clear_archive_playback()

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


if __name__ == "__main__":
    overlay = ArchiveOverlay()
    monitor = ArchivePlaybackMonitor(overlay)

    while not monitor.abortRequested() and not overlay.acquire_service_lock():
        logger.info("Archive overlay service standby (waiting for active instance)")
        if monitor.waitForAbort(10):
            break

    if not overlay.has_service_lock():
        logger.info("Archive overlay service exiting without lock")
    else:
        player = ArchivePlaybackPlayer(overlay)
        logger.info("Archive overlay service started")
        try:
            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
        finally:
            overlay.hide(destroy=True, reset_fullscreen=True)
            clear_archive_playback()
            overlay.release_service_lock()
            logger.info("Archive overlay service stopped")
