# -*- coding: utf-8 -*-
"""Answers of the Webshare search kept on disk: the same title does not ask the server again (TTL).

Every search goes through WebshareClient.api_call. An answer holds the list of files, never the login token: the token
is no part of the key, and a stream link is always asked for when something plays. Only an answer with files is kept,
so a title that appears on the server later is found.
"""
import hashlib
import json
import os
import time

import xbmcvfs

ROOT = 'special://profile/addon_data/plugin.video.milionar/webshare_search/'
TTL = 6 * 3600                           # seconds
MAX_FILES = 400


class Answer(object):
    """What the callers read of a server's response."""

    def __init__(self, content):
        self.content = content
        self.status_code = 200

    @property
    def text(self):
        return self.content.decode('utf-8', 'replace')


def _path(data):
    query = sorted((key, str(value)) for key, value in data.items() if key != 'wst')
    return os.path.join(xbmcvfs.translatePath(ROOT), hashlib.sha1(json.dumps(query).encode('utf-8')).hexdigest() + '.xml')


def get(data, now=None):
    """The kept answer of this search, or None."""
    path = _path(data)
    try:
        if (now or time.time()) - os.path.getmtime(path) >= TTL:
            return None
        with open(path, 'rb') as handle:
            return Answer(handle.read())
    except OSError:
        return None


def put(data, response):
    content = getattr(response, 'content', b'') or b''
    if getattr(response, 'status_code', 200) != 200 or b'<status>OK</status>' not in content or b'<ident>' not in content:
        return
    path = _path(data)
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        temporary = '{}.{}.tmp'.format(path, os.getpid())
        with open(temporary, 'wb') as handle:
            handle.write(content)
        os.replace(temporary, path)
        files = sorted((entry for entry in os.scandir(os.path.dirname(path)) if entry.name.endswith('.xml')),
                       key=lambda entry: entry.stat().st_mtime, reverse=True)
        for entry in files[MAX_FILES:]:
            os.remove(entry.path)
    except OSError:
        pass
