# -*- coding: utf-8 -*-
# Modified resolving to use script.module.resolveurl and the plugin.video.resolveurl-tester to play url if YouTubeDL Fails to Resolve
# Last Updated: 2019-09-02
# Updated By: moedje
# URL: https://www.github.com/moedje/kodi-repo-gaymods
import json
import os
import sys
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
quote = None
try:
    from urllib2 import quote
except:
    quote = None
if quote is None:
    try:
        from urllib import quote
    except:
        quote = None
if quote is None:
    try:
        from urllib.parse import quote
    except:
        quote = None
def myquote(url):
    return url.replace(":","%3A").replace("?", '%3F').replace('+', '%2B').replace('&','%26')
if quote is None:
    quote = myquote

class replacement_stderr(sys.stderr.__class__):
    def isatty(self): return False

sys.stderr.__class__ = replacement_stderr

def debug(content):
    log(content, xbmc.LOGDEBUG)


def notice(content):
    log(content, xbmc.LOGNOTICE)


def log(msg, level=xbmc.LOGNOTICE):
    addon = xbmcaddon.Addon()
    addonID = addon.getAddonInfo('id')
    xbmc.log('%s: %s' % (addonID, msg), level)




from contextlib import closing
from xbmcvfs import File

# fixes python caching bug in youtube-dl
def patchYoutubeDL():
    
    # if there is no comment between `ValueError:` and `pass` then we haven't patched this section before
    toBePatched = """
        except ValueError:
            pass
""" 

    # The comment between `ValueError:` and `pass` ensures we won't patch it repeatedly
    patch = """
        except ValueError:
            # Start: patched by SendToKodi
            pass
        except TypeError:
            pass
            # End: patched by SendToKodi
"""

    addonPath = xbmcaddon.Addon().getAddonInfo('path') 
    youtubeDlPath = addonPath + "/youtube_dl"
    utilsPyPath = youtubeDlPath + '/utils.py'

    # Borrowed from https://forum.kodi.tv/showthread.php?tid=315590
    with closing(File(utilsPyPath, 'r')) as fo:
        fileData = fo.read()

    dataToWrite = fileData.replace(toBePatched, patch)

    with closing(File(utilsPyPath, 'w')) as fo:
        fo.write(dataToWrite)

patchYoutubeDL()

from youtube_dl import YoutubeDL


def showInfoNotification(message):
    xbmcgui.Dialog().notification("SendToKodi", message, xbmcgui.NOTIFICATION_INFO, 5000)


def showErrorNotification(message):
    xbmcgui.Dialog().notification("SendToKodi", message,
                                  xbmcgui.NOTIFICATION_ERROR, 5000)


# Get the plugin url in plugin:// notation.
__url__ = sys.argv[0]
# Get the plugin handle as an integer number.
__handle__ = int(sys.argv[1])


def getParams():
    result = {}
    paramstring = sys.argv[2]
    additionalParamsIndex = paramstring.find(' ')
    if additionalParamsIndex == -1:
        result['url'] = paramstring[1:]
        result['ydlOpts'] = {}
    else:
        result['url'] = paramstring[1:additionalParamsIndex]
        additionalParamsString = paramstring[additionalParamsIndex:]
        additionalParams = json.loads(additionalParamsString)
        result['ydlOpts'] = additionalParams['ydlOpts']
    return result


def createListItemFromVideo(video):
    debug(video)
    url = video['url']
    thumbnail = video.get('thumbnail')
    title = video['title']
    list_item = xbmcgui.ListItem(title, path=url)
    list_item.setInfo(type='Video', infoLabels={'Title': title})

    if thumbnail is not None:
        list_item.setArt({'thumb': thumbnail})

    return list_item



ydl_opts = {
    'format': 'best'
}

params = getParams()
url = str(params['url'])
ydl_opts.update(params['ydlOpts'])
ydl = YoutubeDL(ydl_opts)
ydl.add_default_info_extractors()
oldresult = {}
with ydl:
    showInfoNotification("resolving stream(s) for " + url)
    result = ydl.extract_info(url, download=False)
failed = True
if 'entries' in result:
    # Playlist
    pl = xbmc.PlayList(1)
    pl.clear()
    for video in result['entries']:
        list_item = createListItemFromVideo(video)
        xbmc.PlayList(1).add(list_item.getPath(), list_item)
    xbmc.Player().play(pl)
    showInfoNotification("playing playlist " + result['title'])
    failed = False
else:
    try:
        playpath = 'plugin://plugin.video.resolveurl-tester/?action=play&url={0}'.format(quote(url))
        playtitle = url.split('//',1)[-1].rpartition('/')[-1].title()
        playitem = xbmcgui.ListItem(label=playtitle, path=playpath)        
        playitem.setInfo(type='Video', infoLabels={'Title': playtitle})
        playitem.setProperty('IsPlayable', 'true')
        oldresult = result
        result = None
        failed = False
        showInfoNotification("ResolveURL Playing: " + url)
    except:
        failed = True
if failed:
    # Try just playing with Kodi Just a video, pass the item to the Kodi player.
    if result is not None:
        showInfoNotification("playing title " + result['title'])
        playitem = createListItemFromVideo(result)
xbmcplugin.setResolvedUrl(__handle__, True, listitem=playitem)
