import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
import urllib.parse
import time

from ..plugin import Plugin
from resources.lib.util.common import do_log

class scriptrun(Plugin):
    name = "external script"
    priority = 100
    
    AUTORUN_ADDONS = [
        'script.kodi.loguploader',
    ]
    
    def routes(self, plugin):
        @plugin.route("/run_script/<path:url>")
        def run_script(url):
            xbmc.log(f'[{self.name}] : url = {url} ', 3)
            
            decoded_url = urllib.parse.unquote_plus(url)
            xbmc.log(f'[{self.name}] : decoded_url = {decoded_url} ', 3)
            
            if '?' in decoded_url or '=' in decoded_url:
                script_link = urllib.parse.parse_qs(urllib.parse.urlparse(decoded_url).query)
                script = script_link.get('script', [''])[0]
                script_args = script_link.get('args', [])
            else:
                script = decoded_url
                script_args = []
            
            if not script:
                xbmc.log(f'[{self.name}] : No script specified', 3)
                return
                
            xbmc.log(f'[{self.name}] : script = {script}, args = {script_args}', 3)
            
            is_addon = True    
            
            if script.startswith('special://'):
                script = xbmcvfs.translatePath(script)
                is_addon = False
            
            processed_args = []
            for args in script_args:
                if args.startswith('special://'):
                    processed_args.append(xbmcvfs.translatePath(args))
                else:
                    processed_args.append(args)
            
            if len(processed_args) >= 2:
                script_args_str = ','.join(processed_args)
            elif len(processed_args) == 1:
                script_args_str = processed_args[0]
            else:
                script_args_str = ''
            
            if is_addon:
                if not xbmc.getCondVisibility(f'System.HasAddon({script})'):
                    xbmc.log(f'[{self.name}] : Installing addon: {script}', 3)
                    xbmc.executebuiltin(f'InstallAddon({script})')
                    
                    for i in range(15):
                        time.sleep(1)
                        if xbmc.getCondVisibility(f'System.HasAddon({script})'):
                            xbmc.log(f'[{self.name}] : Addon installed after {i+1} seconds', 3)
                            break
                    
                    xbmc.executebuiltin('Container.Refresh')
                
                if script in self.AUTORUN_ADDONS and xbmc.getCondVisibility(f'System.HasAddon({script})'):
                    xbmc.log(f'[{self.name}] : Running addon: {script}', 3)
                    if script_args_str:
                        xbmc.executebuiltin(f'RunScript({script},{script_args_str})')
                    else:
                        xbmc.executebuiltin(f'RunScript({script})')
                else:
                    xbmc.log(f'[{self.name}] : Addon not in autorun list or not installed', 3)
                
            else:
                if not xbmcvfs.exists(script):
                    return
                    
                if script_args_str:
                    xbmc.executebuiltin(f'RunScript({script},{script_args_str})')
                else:
                    xbmc.executebuiltin(f'RunScript({script})')