# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import sys
import os
import time
import hashlib
import requests

from six import PY3
try:
    from kodi_six import xbmcaddon, xbmc, xbmcvfs
except:
    pass
translate_ = xbmcvfs.translatePath if PY3 else xbmc.translatePath
URL_BASE = 'https://zoreu.github.io/remote_spartan/config.json'

if not PY3:
    try:
        reload(sys)
        sys.setdefaultencoding('utf-8')
    except:
        pass


class plugin:
    def __init__(self):
        self.url = URL_BASE
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        }
        self.api = self.data_json()
        self.addon_ = xbmcaddon.Addon()
        self.cache_dir = translate_(os.path.join(self.addon_.getAddonInfo('profile'), 'cache'))    

        if not xbmcvfs.exists(self.cache_dir):
            xbmcvfs.mkdirs(self.cache_dir)

    def data_json(self):
        try:
            response = requests.get(self.url, headers=self.headers)
            response.encoding = 'utf-8'
            return response.json()
        except:
            return {}

    def _cache_path(self, url):
        # gera um nome único baseado na URL
        name = hashlib.md5(url.encode('utf-8')).hexdigest()
        return os.path.join(self.cache_dir, name + '.cache')

    def import_script(self, url):
        ENABLE_CACHE = self.api.get('enable_cache', False)
        if ENABLE_CACHE:
            cache_file = self._cache_path(url)

            # verifica cache
            if os.path.exists(cache_file):
                age = time.time() - os.path.getmtime(cache_file)
                if age < int(self.api.get('cache_time', 3600)):
                    try:
                        with open(cache_file, 'r') as f:
                            code = f.read()
                        exec(code, globals())
                        return
                    except:
                        pass  # se falhar, baixa de novo

        # baixa da internet
        try:
            response = requests.get(url, headers=self.headers)
            if PY3:
                response.encoding = 'utf-8'
                code = response.text
            else:
                # Python 2: usar bytes
                code = response.content
        except:
            code = ''
        if ENABLE_CACHE:
            # salva no cache
            if code:
                try:
                    with open(cache_file, 'w') as f:
                        f.write(code)
                except:
                    pass
        if code:
            exec(code, globals())

    def main(self):
        base = self.api.get('host', 'http://localhost') + '/' + self.api.get('version', '01')

        for imp in self.api.get('imports', []):
            self.import_script(base + '/' + imp)

        self.import_script(base + '/' + self.api.get('main', 'app.py'))


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