# -*- coding: utf-8 -*-
import os
import sys

from kodi_six import xbmcaddon

ADDON = xbmcaddon.Addon()
ADDON_ID = ADDON.getAddonInfo("id")
ADDON_NAME = ADDON.getAddonInfo("name")
ADDON_ICON = ADDON.getAddonInfo("icon")
# BEGIN ElementumService-patched: globals
#ADDON_VERSION = ADDON.getAddonInfo("version")
ADDON_VERSION = ADDON.getAddonInfo('version')
GLOBALS = {}

def makeAddon(id, info):
    import shutil
    fanartPng = os.path.join(ADDON_PATH, 'fanart.png')
    iconPng = os.path.join(ADDON_PATH, 'icon.png')
    idDir = os.path.join(ADDON_PATH, '..', id)
    infoFile = os.path.join(idDir, 'addon.xml')
    if os.path.exists(infoFile):
        try:
            with open(infoFile, 'r') as f:
                if info == f.read():
                    return True
        except Exception:
            pass
    try:
        shutil.rmtree(idDir, True)
        os.makedirs(idDir)
        with open(infoFile, 'w') as f:
            f.write(info)
        shutil.copy(fanartPng, os.path.join(idDir, 'fanart.png'))
        shutil.copy(iconPng, os.path.join(idDir, 'icon.png'))
        return True
    except Exception:
        pass
    return False

def installAddon(id):
    import time
    from kodi_six import xbmc
    from elementum.provider import parse_json
    try:
        detailsJson = '{"jsonrpc":"2.0","id":"1","method":"Addons.GetAddonDetails","params":{"addonid":"%s","properties":["installed","enabled"]}}' % id
        enableJson = '{"jsonrpc":"2.0","id":"1","method":"Addons.SetAddonEnabled","params":{"addonid":"%s","enabled":true}}' % id
        addon = parse_json(xbmc.executeJSONRPC(detailsJson)).get('result', {}).get('addon', {})
        if addon.get('installed', False):
            if not addon.get('enabled', False):
                xbmc.executeJSONRPC(enableJson)
            return
        xbmc.executebuiltin('UpdateLocalAddons')
        xbmc.executebuiltin('InstallAddon(%s)' % id)
        for _ in range(10):
            addon = parse_json(xbmc.executeJSONRPC(detailsJson)).get('result', {}).get('addon', {})
            if addon.get('installed', False):
                break
            time.sleep(1.0)
        xbmc.executeJSONRPC(enableJson)
        xbmc.executebuiltin('UpdateLocalAddons')
        xbmc.executebuiltin('UpdateAddonRepos')
    except Exception:
        pass

def startApp(args):
    import six
    from kodi_six import xbmc
    dataFragment = '%00'.join(six.moves.urllib_parse.quote(arg, '') for arg in args)
    dataSuffix = '#' + dataFragment if dataFragment != '' else ''
    xbmc.executebuiltin('StartAndroidActivity(service.elementum.android, android.intent.action.MAIN, , version:0.1.1140001%s)' % dataSuffix)

def recvData(port):
    import socket
    try:
        chunks = []
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
            client.connect(('127.0.0.1', port))
            while True:
                chunk = client.recv(0x2000)
                if not chunk:
                    break
                chunks.append(chunk)
        return b''.join(chunks)
    except Exception:
        pass
    return b''

def recvApp(expected, args):
    import time
    remotePort = ADDON.getSetting('remote_port')
    port = 65220
    if remotePort != '':
        port = int(remotePort)
        args.append('-localPort=' + remotePort)
    startApp(args)
    expectedB = expected.encode()
    for _ in range(100):
        data = recvData(port)
        if expectedB in data:
            return data
        time.sleep(0.1)
    return b''

def populateGlobals():
    data = recvApp('service.elementum.android', ['-translatePath'])
    if data != b'':
        with open(os.path.join(ADDON_PATH, '.globals'), 'wb') as f:
            f.write(data)
        return True
    return False

def getGlobals():
    if GLOBALS:
        return GLOBALS
    with open(os.path.join(ADDON_PATH, '.globals'), 'r') as f:
        homeDirReplacement, xbmcDirReplacement = f.read().split('\0')
        GLOBALS['special://home'] = homeDirReplacement
        GLOBALS['special://xbmc'] = xbmcDirReplacement
    return GLOBALS

def retryStartApp():
    if populateGlobals():
        args = []
        if ADDON.getSetting('local_port') != '':
            args.append('-remotePort=' + ADDON.getSetting('local_port'))
        if ADDON.getSetting('remote_host') != '':
            args.append('-localHost=' + ADDON.getSetting('remote_host'))
        if ADDON.getSetting('remote_port') != '':
            args.append('-localPort=' + ADDON.getSetting('remote_port'))
        startApp(args)
# END ElementumService-patched: globals

try:
    ADDON_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__).decode(sys.getfilesystemencoding(), 'ignore')), "..", "..", ".."))
except:
    ADDON_PATH = ADDON.getAddonInfo("path")
