# -*- coding: utf-8 -*-
import os
import sys
from kodi_six import xbmc, xbmcgui, xbmcplugin, xbmcaddon, xbmcvfs
import shutil

try:
    from xbmcvfs import translatePath
except (ImportError, AttributeError):
    from xbmc import translatePath

from lib.service import log, search_subtitle, download_subtitle

__addon__ = xbmcaddon.Addon()
__author__     = __addon__.getAddonInfo('author')
__scriptid__   = __addon__.getAddonInfo('id')
__scriptname__ = __addon__.getAddonInfo('name')
__version__    = __addon__.getAddonInfo('version')

__profile__    = translatePath(__addon__.getAddonInfo('profile'))
__temp__       = translatePath(os.path.join(__profile__,'temp',''))

if xbmcvfs.exists(__temp__):
    shutil.rmtree(__temp__)
xbmcvfs.mkdirs(__temp__)


def get_params(string=""):
    param=[]
    if string == "":
        paramstring=sys.argv[2]
    else:
        paramstring=string
    if len(paramstring)>=2:
        params=paramstring
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]
    return param

params = get_params()

if params['action'] == 'search' or params['action'] == 'manualsearch':
    log(__name__, "action '%s' called" % params['action'])
    PreferredSub = params.get('preferredlanguage')
    if 'searchstring' in params:
        text = params['searchstring']
        search_subtitle(PreferredSub, manual_search=text)
    elif params['action'] == 'search':
        search_subtitle(PreferredSub)
elif params['action'] == 'download':
    log(__name__, "action '%s' called" % params['action'])
    if 'sub_download' in params:
        link_sub = params['sub_download']
        download_subtitle(link_sub)