# -*- coding: utf-8 -*-
"""What the addon saves with Kodi's texts, after an update without a restart (docs/plan/skin-milionar/251 §5):
empty row titles are filled, Home's saving actions wait for the reload, a row made with old texts is built again.

Run: python3 scripts/library_harness/test_texts_saved.py
"""
import os
import re
import sys
import unittest

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

stubs.install()

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

from wcs.skin import journal, local, slots  # noqa: E402


class SavedTextsTests(unittest.TestCase):
    def setUp(self):
        self.strings, self.commands, self.props = {}, [], {}
        self._exec, self._info = xbmc.executebuiltin, xbmc.getInfoLabel
        xbmc.executebuiltin = self.fake_exec
        xbmc.getInfoLabel = self.fake_info
        xbmcaddon.Addon.strings.update({33155: 'Živě', 33147: 'Ze studia', 33156: 'Záznamy', 32501: 'Kurátor'})

    def tearDown(self):
        xbmc.executebuiltin, xbmc.getInfoLabel = self._exec, self._info

    def fake_exec(self, command, wait=False):
        self.commands.append(command)
        match = re.match(r'Skin\.SetString\((.*?),"(.*)"\)$', command)
        if match:
            self.strings[match.group(1)] = match.group(2)

    def fake_info(self, label):
        match = re.match(r'Skin\.String\((.*)\)$', label)
        if match:
            return self.strings.get(match.group(1), '')
        match = re.match(r'Window\(Home\)\.Property\((.*)\)$', label)
        if match:
            return self.props.get(match.group(1), '')
        return 'Czech' if label == 'System.Language' else ''

    def test_empty_titles_of_typed_rows_are_filled_and_others_stay(self):
        # Standa's TV, 2026-11-09: the three Vinyl radio rows had a type and no title
        self.strings.update({'mil.vinyl.1.type': 'vinyl_curator', 'mil.vinyl.1.title': 'Můj výběr',
                             'mil.vinyl.2.type': 'vinyl_radio_live', 'mil.vinyl.3.type': 'vinyl_radio_studio',
                             'mil.vinyl.9.type': 'vinyl_radio_records', 'mil.vinyl.4.type': 'off'})
        repaired = slots.repair_titles()
        self.assertEqual(sorted(repaired), ['mil.vinyl.2.', 'mil.vinyl.3.', 'mil.vinyl.9.'])
        self.assertEqual((self.strings['mil.vinyl.2.title'], self.strings['mil.vinyl.3.title'],
                          self.strings['mil.vinyl.9.title']), ('Živě', 'Ze studia', 'Záznamy'))
        self.assertEqual(self.strings['mil.vinyl.1.title'], 'Můj výběr')
        self.assertNotIn('mil.vinyl.4.title', self.strings)
        self.commands.clear()
        self.assertEqual(slots.repair_titles(), [])
        self.assertEqual(self.commands, [])

    def test_an_empty_text_is_never_written(self):
        self.strings['mil.vinyl.2.type'] = 'vinyl_radio_live'
        saved = xbmcaddon.Addon.strings.pop(33155)
        try:
            self.assertEqual(slots.repair_titles(), [])
        finally:
            xbmcaddon.Addon.strings[33155] = saved

    def test_saving_actions_wait_for_the_reload(self):
        ran = []
        original = slots.run
        slots.run = lambda params: ran.append(params['action'])
        try:
            self.props['milionar.texts.reloading'] = '1'
            for action in local.SAVING:
                if action.startswith(('skin_slots', 'skin_defaults', 'skin_genres', 'skin_services', 'skin_radio')):
                    self.assertTrue(local.run({'action': action}))
            self.assertEqual(ran, [])
            self.assertTrue(local.run({'action': 'skin_slots'}))             # not a saving action: runs
            self.assertEqual(ran, ['skin_slots'])
            del self.props['milionar.texts.reloading']
            local.run({'action': 'skin_genres_defaults'})
            self.assertEqual(ran, ['skin_slots', 'skin_genres_defaults'])
        finally:
            slots.run = original

    def test_every_home_saving_action_is_gated(self):
        root = os.path.dirname(os.path.dirname(HERE))
        for path in ('resources/skin.milionar/xml/Home.xml', 'resources/skin-modules/layouts/horizontal/xml/Home.xml'):
            with open(os.path.join(root, path), encoding='utf-8') as handle:
                actions = set(re.findall(r'<onload[^>]*>RunPlugin\(plugin://plugin\.video\.milionar/\?action=(\w+)',
                                         handle.read()))
            self.assertTrue(actions)
            self.assertLessEqual(actions, set(local.SAVING), path)

    def test_a_row_made_with_old_texts_has_another_signature(self):
        params = {'row': 'fy_new', 'sec': 'foryou', 'slot': '8'}
        self.props['milionar.texts'] = ''                      # Kodi held the texts of the version before
        stale = journal.signature(params)
        self.props['milionar.texts'] = 'texts-dcbdc953b728233f'
        current = journal.signature(params)
        self.assertNotEqual(stale, current)
        self.assertEqual(current, journal.signature(params))


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