# -*- coding: utf-8 -*-
"""Actors of the simulator: a device process (killable, restartable on its own profile) and the web user.

DeviceHandle talks JSON lines to device_proc.py (the real addon code on stubs). WebActor uses the harness helper:
`/web` = the web API with the user's cookie session (the routes the browser uses), `/progress` = the playback route's
saveProgress, `/db` = read-only SQL for the `at` of what the web just wrote."""
import json
import os
import select
import subprocess
import sys
import time
import urllib.parse
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))


def http_json(url, body=None, timeout=30):
    data = None if body is None else json.dumps(body).encode()
    request = urllib.request.Request(url, data=data, headers={'content-type': 'application/json'})
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return json.loads(response.read().decode() or 'null')


class DeviceDied(Exception):
    pass


class DeviceHandle(object):
    def __init__(self, name, profile, server, helper, clock=None):
        self.name, self.profile, self.server, self.helper, self.clock = name, profile, server, helper, clock
        self.proc = None
        self.restarts = 0
        self.start()

    def start(self):
        env = dict(os.environ, SIM_PROFILE=self.profile, PYTHONDONTWRITEBYTECODE='1')
        if self.clock:
            env['SIM_CLOCK'] = self.clock
        self.proc = subprocess.Popen([sys.executable, '-B', os.path.join(HERE, 'device_proc.py'), self.server, self.helper],
                                     stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env,
                                     text=True, bufsize=1)

    def _send(self, method, args):
        self.proc.stdin.write(json.dumps({'method': method, 'args': list(args)}) + '\n')
        self.proc.stdin.flush()

    def _read(self, timeout=None):
        if timeout is not None:
            ready, _w, _x = select.select([self.proc.stdout], [], [], timeout)
            if not ready:
                return None
        line = self.proc.stdout.readline()
        if not line:
            raise DeviceDied('{} exited'.format(self.name))
        reply = json.loads(line)
        if not reply.get('ok'):
            raise RuntimeError('{} {}: {}\n{}'.format(self.name, reply.get('error'), '', reply.get('trace', '')))
        return reply

    def call(self, method, *args):
        self._send(method, args)
        return self._read()['result']

    def call_or_kill(self, kill_after, method, *args):
        """Run a command, but kill the process if it is still running after `kill_after` s (then restart it, which
        resumes an interrupted switch as Kodi's service does). Returns (result or None, killed)."""
        self._send(method, args)
        reply = self._read(timeout=kill_after)
        if reply is not None:
            return reply['result'], False
        self.kill()
        self.start()
        self.restarts += 1
        return None, True

    def kill(self):
        try:
            self.proc.kill()
            self.proc.wait(timeout=5)
        except Exception:
            pass

    def close(self):
        try:
            self.proc.stdin.close()
            self.proc.wait(timeout=5)
        except Exception:
            self.kill()


class WebActor(object):
    def __init__(self, helper, email):
        self.helper, self.email = helper.rstrip('/'), email
        self.user_id = None

    def db(self, sql):
        return http_json(self.helper + '/db?sql=' + urllib.parse.quote(sql))

    def uid(self):
        if self.user_id is None:
            self.user_id = self.db("SELECT id FROM users WHERE email = '{}'".format(self.email))[0]['id']
        return self.user_id

    def web(self, method, path, body=None):
        return http_json(self.helper + '/web', {'user': self.email, 'method': method, 'path': path, 'body': body})

    def watch_row(self, key):
        parts = key.split(':')
        if parts[0] == 'movie':
            where = "media_type='movie' AND tmdb_id={} AND season IS NULL AND episode IS NULL".format(int(parts[1]))
        else:
            where = "media_type='tv' AND tmdb_id={} AND season={} AND episode={}".format(*(int(p) for p in parts[1:]))
        rows = self.db('SELECT playcount, watched, position, at FROM watch_state WHERE user_id={} AND {}'.format(self.uid(), where))
        return rows[0] if rows else None

    def tomb_at(self, entity, key):
        rows = self.db("SELECT at FROM account_tombstones WHERE user_id={} AND entity='{}' AND key='{}'".format(self.uid(), entity, key))
        return rows[0]['at'] if rows else None

    def progress(self, key, position, duration):
        parts = key.split(':')
        body = {'user': self.email, 'mediaType': parts[0], 'tmdbId': int(parts[1]), 'position': position, 'duration': duration,
                'ended': False}
        if parts[0] == 'tv':
            body.update(season=int(parts[2]), episode=int(parts[3]))
        before = self.watch_row(key)
        http_json(self.helper + '/progress', body)
        row = self.watch_row(key)
        if not row or (before and row['at'] == before['at'] and row['position'] == before['position']
                       and row['playcount'] == before['playcount']):
            return []
        finished = before is None and row['playcount'] > 0 or before is not None and row['playcount'] > before['playcount']
        return [{'type': 'watched' if finished else 'progress', 'key': key, 'at': row['at'],
                 'payload': {'pos': row['position']}}]

    def episodes(self, key, watched):
        _tv, show, season, episode = key.split(':')
        self.web('POST', '/api/library/episodes/tv/{}'.format(show), {'season': int(season), 'episodes': [int(episode)], 'watched': watched})
        if watched:
            row = self.watch_row(key)
            return [{'type': 'mark', 'key': key, 'at': row['at'], 'payload': {}}] if row else []
        at = self.tomb_at('watch', key)
        return [{'type': 'unwatched', 'key': key, 'at': at, 'payload': {}}] if at else []

    def list_set(self, key, on):
        media, tmdb_id = key.split(':')
        if on:
            self.web('POST', '/api/library', {'mediaType': media, 'tmdbId': int(tmdb_id)})
            rows = self.db("SELECT at FROM library_items WHERE user_id={} AND media_type='{}' AND tmdb_id={}".format(self.uid(), media, int(tmdb_id)))
            at = rows[0]['at'] if rows else None
        else:
            self.web('DELETE', '/api/library/{}/{}'.format(media, tmdb_id))
            at = self.tomb_at('library', key)
        return [{'type': 'list_set', 'key': key, 'at': at, 'payload': {'in_list': on}}] if at else []

    def channels(self):
        return self.db('SELECT id, uuid, name, channel_type, at FROM channels WHERE user_id={}'.format(self.uid()))

    def channel_create(self, kind, name):
        created = self.web('POST', '/api/channels', {'name': name, 'type': kind})
        channel_id = (created.get('body') or {}).get('id')
        rows = [c for c in self.channels() if c['id'] == channel_id]
        return [{'type': 'channel_create', 'key': rows[0]['uuid'], 'at': rows[0]['at'], 'payload': {'name': name}}] if rows else []

    def channel_rename(self, channel, name):
        self.web('PATCH', '/api/channels/{}'.format(channel['id']), {'name': name})
        rows = [c for c in self.channels() if c['id'] == channel['id']]
        return [{'type': 'channel_rename', 'key': channel['uuid'], 'at': rows[0]['at'], 'payload': {'name': name}}] if rows else []

    def channel_delete(self, channel):
        self.web('DELETE', '/api/channels/{}'.format(channel['id']))
        return [{'type': 'channel_delete', 'key': channel['uuid'], 'at': int(time.time() * 1000), 'payload': {}}]

    def channel_item(self, channel, media, tmdb_id, on):
        if on:
            self.web('POST', '/api/channels/{}/items'.format(channel['id']), {'mediaType': media, 'tmdbId': tmdb_id, 'title': 'T{}'.format(tmdb_id)})
        else:
            rows = self.db('SELECT id FROM channel_items WHERE channel_id={} AND tmdb_id={}'.format(channel['id'], tmdb_id))
            for row in rows:
                self.web('DELETE', '/api/channels/{}/items/{}'.format(channel['id'], row['id']))
        return []

    def setting(self, key, value):
        self.web('PUT', '/api/settings', {'values': {key: value}})
        return []

    def feedback(self, key, value):
        media, tmdb_id = key.split(':')
        self.web('POST', '/api/foryou/feedback', {'mediaType': media, 'tmdbId': int(tmdb_id), 'value': value})
        return []
