# -*- coding: utf-8 -*-
"""Kodi's background progress of the account (wcs/account/progress.py): a sign-in and a large page show it, the live
sync stays silent, it lasts while the page is applied and the journal builds rows, and never during playback.

python3 -B scripts/account_harness/test_progress.py"""
import os
import sys
import time
import unittest
from unittest import mock

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), 'library_harness'))
import stubs  # noqa: E402

stubs.install()

import xbmc  # noqa: E402
import xbmcgui  # noqa: E402

from wcs.account import progress  # noqa: E402
from wcs.skin import journal  # noqa: E402


class WaitingMonitor(xbmc.Monitor):
    """Waits like Kodi's: the stub returns at once and the progress threads would spin (a flaky count of updates)."""
    def waitForAbort(self, timeout=0):
        time.sleep(min(timeout or 0, 0.5))
        return False


xbmc.Monitor = WaitingMonitor


def wait_closed(timeout=3.0):
    deadline = time.time() + timeout
    while progress.active() and time.time() < deadline:
        time.sleep(0.01)
    return not progress.active()


class ProgressTests(unittest.TestCase):
    def setUp(self):
        progress.finish()
        del xbmcgui.PROGRESS[:]
        journal._building.clear()
        journal._wake.clear()
        self.playing = False
        xbmc.getCondVisibility = lambda cond: self.playing if cond == 'Player.HasMedia' else False

    def tearDown(self):
        journal._building.clear()
        journal._wake.clear()
        progress.finish()
        xbmc.getCondVisibility = lambda cond: False

    def test_live_sync_stays_silent(self):
        self.assertFalse(progress.begin_changes(progress.LARGE - 1))
        self.assertFalse(progress.active())
        self.assertEqual(xbmcgui.PROGRESS, [])

    def test_large_page_lasts_while_applied_and_rows_build(self):
        self.assertTrue(progress.begin_changes(120))
        self.assertEqual(xbmcgui.PROGRESS[0][0], 'create')
        time.sleep(0.05)
        self.assertTrue(progress.active(), 'held while the page is applied')
        journal._building.set()
        progress.release()
        progress.rows(3, 10)
        self.assertEqual(xbmcgui.PROGRESS[-1][0:2], ('update', 37))
        time.sleep(0.05)
        self.assertTrue(progress.active(), 'open while the journal builds rows')
        journal._building.clear()
        self.assertTrue(wait_closed())
        self.assertEqual(xbmcgui.PROGRESS[-1], ('close',))

    def test_signin_closes_when_the_journal_is_idle(self):
        journal._wake.set()                            # rows asked for, not yet looked at
        progress.begin_signin()
        time.sleep(0.05)
        self.assertTrue(progress.active())
        journal._wake.clear()
        self.assertTrue(wait_closed())

    def test_merge_counts_its_ops_then_closes(self):
        left = [3]
        self.assertFalse(progress.begin_merge(lambda: 0), 'nothing queued: no progress')
        self.assertTrue(progress.begin_merge(lambda: left[0]))
        self.assertEqual(xbmcgui.PROGRESS[0][0], 'create')
        progress.rows(1, 10)                           # the rows wait while the merge owns the message
        self.assertNotEqual(xbmcgui.PROGRESS[-1][0:2], ('update', 19))
        count = len(xbmcgui.PROGRESS)
        self.assertTrue(progress.begin_changes(80))    # a page of the merge's answers: held, no new message
        self.assertEqual(len(xbmcgui.PROGRESS), count)
        progress.release()
        time.sleep(0.05)
        self.assertTrue(progress.active(), 'held while merge ops wait in the outbox')
        left[0] = 0
        self.assertTrue(wait_closed())

    def test_signin_lasts_until_the_titles_and_pro_tebe_are_in(self):
        # after a sign-in the rows show what is cached and the cards of Pokračovat follow one title at a time
        # (Windows Kodi, Standa 2026-11-09): the bar stays until the titles' data and Pro tebe of the account are in
        from wcs.foryou import service as foryou_service
        from wcs.skin import service as skin_service
        building = [True]
        with mock.patch.object(foryou_service, 'building', lambda: building[0]):
            skin_service._loading['titles'] = 4
            progress.begin_signin()
            time.sleep(progress.IDLE_S + 1.0)
            self.assertTrue(progress.active(), 'open while titles are on the way')
            self.assertEqual(xbmcgui.PROGRESS[-1][0:2], ('update', 10))
            skin_service._loading['titles'] = 1
            time.sleep(0.7)
            self.assertEqual(xbmcgui.PROGRESS[-1][0:2], ('update', 73))
            skin_service._loading['titles'] = 0
            time.sleep(progress.IDLE_S + 1.0)
            self.assertTrue(progress.active(), 'open while Pro tebe of the account is built')
            building[0] = False
            self.assertTrue(wait_closed(progress.IDLE_S + 2.0))
        skin_service._loading.update(titles=0, rows=False)

    def test_never_during_playback(self):
        self.playing = True
        progress.begin_signin()
        self.assertFalse(progress.active())
        self.playing = False
        journal._building.set()
        progress.begin_signin()
        self.assertTrue(progress.active())
        self.playing = True                            # a film starts: the progress goes away
        self.assertTrue(wait_closed())


if __name__ == '__main__':
    unittest.main()
