# -*- coding: utf-8 -*-
"""Webshare readiness: a login, or an account session token delivered without a login (T9, account sync A10)."""
import os
import sys
import unittest

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

stubs.install()

import xbmcaddon  # noqa: E402

from wcs import user_data  # noqa: E402
from wcs.account import state  # noqa: E402


class WebshareReadyTests(unittest.TestCase):
    def setUp(self):
        self.saved = dict(xbmcaddon.Addon.settings)
        for key in ('wsuser', 'wspass', 'token', state.TOKEN):
            xbmcaddon.Addon.settings[key] = ''
        state.invalidate()

    def tearDown(self):
        xbmcaddon.Addon.settings.clear()
        xbmcaddon.Addon.settings.update(self.saved)
        state.invalidate()

    def ready(self):
        state.invalidate()
        return user_data.webshare_ready(xbmcaddon.Addon())

    def test_login_is_ready(self):
        xbmcaddon.Addon.settings.update({'wsuser': 'u', 'wspass': 'p'})
        self.assertTrue(self.ready())

    def test_token_alone_is_not_ready_without_account(self):
        xbmcaddon.Addon.settings['token'] = 'wst'
        self.assertFalse(self.ready())

    def test_account_token_is_ready(self):
        xbmcaddon.Addon.settings.update({'token': 'wst', state.TOKEN: 'device'})
        self.assertTrue(self.ready())

    def test_account_without_token_is_not_ready(self):
        xbmcaddon.Addon.settings[state.TOKEN] = 'device'
        with self.fetch(None):
            self.assertFalse(self.ready())

    def test_lost_account_token_comes_back_from_the_account(self):
        # an older settings path cleared the token of a token-only account: the account's keys are fetched again
        xbmcaddon.Addon.settings[state.TOKEN] = 'device'
        with self.fetch('wst') as calls:
            self.assertTrue(self.ready())
            self.assertEqual(calls, [1])
            xbmcaddon.Addon.settings['token'] = ''
            self.assertFalse(self.ready())              # a second miss within a minute does not ask the server again
            self.assertEqual(calls, [1])

    def test_own_login_never_fetches(self):
        xbmcaddon.Addon.settings.update({'wsuser': 'u', 'wspass': 'p', state.TOKEN: 'device'})
        with self.fetch('wst') as calls:
            self.assertTrue(self.ready())
            self.assertEqual(calls, [])

    def fetch(self, token):
        import contextlib
        import xbmcgui
        from wcs.account import sync

        @contextlib.contextmanager
        def patched():
            calls = []
            original = sync.fetch_secrets
            xbmcgui.Window(10000).setProperty('milionar.account.ws_restore', '')

            def fake():
                calls.append(1)
                if token:
                    xbmcaddon.Addon.settings['token'] = token
            sync.fetch_secrets = fake
            try:
                yield calls
            finally:
                sync.fetch_secrets = original
                xbmcgui.Window(10000).setProperty('milionar.account.ws_restore', '')
        return patched()


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