#!/usr/bin/env python3
"""Two Kodi devices + the web on the harness backend (WEB scripts/harness/sync-backend.ts must run on 5239/5240).

python3 -B scripts/account_harness/test_two_devices.py"""
import json
import os
import random
import subprocess
import sys
import unittest
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
SERVER, HELPER = os.environ.get('SYNC_BACKEND', 'http://127.0.0.1:5239/'), os.environ.get('SYNC_HELPER', 'http://127.0.0.1:5240')


class Proc(object):
    def __init__(self):
        self.p = subprocess.Popen([sys.executable, '-B', os.path.join(HERE, 'device_proc.py'), SERVER, HELPER],
                                  stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)

    def __getattr__(self, name):
        def call(*args):
            self.p.stdin.write(json.dumps({'method': name, 'args': list(args)}) + '\n')
            self.p.stdin.flush()
            answer = json.loads(self.p.stdout.readline())
            if not answer['ok']:
                raise AssertionError(answer['error'] + '\n' + answer.get('trace', ''))
            return answer['result']
        return call

    def close(self):
        self.p.stdin.close()
        self.p.wait(10)


def web(method, path, body=None, user='A'):
    data = json.dumps({'user': user, 'method': method, 'path': path, 'body': body}).encode()
    request = urllib.request.Request(HELPER + '/web', data=data, headers={'content-type': 'application/json'})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.loads(response.read())


class TwoDevices(unittest.TestCase):
    def setUp(self):
        self.a, self.b = Proc(), Proc()
        self.addCleanup(self.a.close)
        self.addCleanup(self.b.close)
        self.assertTrue(self.a.pair('A'))
        self.assertTrue(self.b.pair('A'))

    def test_progress_watched_lists_channels_settings_flow_between_devices_and_web(self):
        film, show, other = (random.randint(10 ** 6, 10 ** 7) for _ in range(3))
        channel = '11111111-2222-4333-8444-{:012d}'.format(random.randint(0, 10 ** 11))
        self.a.progress('movie', film, 600, 6000)
        self.a.list_add('tv', show, True)
        self.a.channel(channel, 'Sitcomy', [{'id': 1668, 'name': 'Friends'}])
        self.a.setting('mytv_upcoming_count', '20')
        self.assertEqual(self.a.sync()['outbox'], 0)
        self.b.sync()
        state = self.b.dump()
        self.assertEqual(state['movies'].get(str(film)), [0, 600.0])
        self.assertIn('tv:{}'.format(show), state['lists'])
        self.assertEqual(state['channels'].get(channel), ['tv', 'Sitcomy', ['1668']])
        self.assertEqual(state['settings']['mytv_upcoming_count'], '20')
        # the web sees it and its own change reaches both devices
        progress = web('GET', '/api/library/progress/movie/{}'.format(film))
        self.assertEqual(progress['body']['state']['position'], 600)
        web('POST', '/api/library', {'mediaType': 'movie', 'tmdbId': other})
        self.a.sync()
        self.b.sync()
        self.assertIn('movie:{}'.format(other), self.a.dump()['lists'])
        self.assertIn('movie:{}'.format(other), self.b.dump()['lists'])
        # a watched on B, a stale progress on A afterwards: watched wins everywhere
        self.b.watched('movie', film)
        self.b.sync()
        self.a.sync()
        self.assertEqual(self.a.dump()['movies'].get(str(film)), [1, 0.0])

    def test_sign_out_restores_the_devices_own_data(self):
        before = self.a.dump()
        self.a.progress('movie', 27205, 300, 9000)
        self.a.sync()
        self.assertTrue(self.a.signout())
        after = self.a.dump()
        self.assertNotIn('27205', after['movies'])
        self.assertEqual(after['settings'].get('account_name', ''), '')


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