import requests
from urllib.parse import urlencode

try:
    import xbmcgui
    import xbmcplugin
except ImportError:
    pass

ISH = False
try:
    import inputstreamhelper
    ISH = True
except ImportError:
    pass

class ResolvedMediaFile:
    def __init__(self, url, headers, t="hls", self_player=False, license_key=None, license_type=None, drm=None):
        self.url = url
        self.hlsurl = self.url
        self.headers = dict(headers)
        self.falcon_proxy = False
        self.t = t
        self.self_player = self_player
        self.license_key = license_key
        self.license_type = license_type
        self.drm = drm

    def urlencoded(self):
        return self.url + "|" + urlencode(self.headers)
    
    def ish_play(self, handle):
        ext = "mpd" if self.t == "dash" else ""
        isHelper = inputstreamhelper.Helper(ext, drm=self.drm)

        if isHelper.check_inputstream():
            li = xbmcgui.ListItem("Stream", path=self.url)
            li.setProperty('inputstream','inputstream.adaptive')
            li.setProperty('inputstream.adaptive.manifest_type', ext)
            if self.license_type:
                li.setProperty('inputstream.adaptive.license_type', self.license_type)
            if self.license_key:
                li.setProperty('inputstream.adaptive.license_key', self.license_key)
            li.setProperty('inputstream.adaptive.stream_headers', urlencode(dict(self.headers)))
            li.setMimeType('application/dash+xml' if self.t == "dash" else "")
            li.setContentLookup(False)
            xbmcplugin.setResolvedUrl(handle, True, li)
        else:
            xbmcgui.Dialog().ok("Error", "No inputstream helper found")

    def play(self, handle):
        if self.self_player == False: return
        
        if self.license_key and ISH:
            self.ish_play(handle)
            return
        if self.license_key and not ISH:
            xbmcgui.Dialog().ok("Error", "No inputstream helper found")
            return


        ext = "mpd" if self.t == "dash" else ""

        li = xbmcgui.ListItem("Stream", path=self.url)
        li.setProperty('inputstream','inputstream.adaptive')
        li.setProperty('inputstream.adaptive.manifest_type', ext)
        li.setProperty('inputstream.adaptive.stream_headers', urlencode(dict(self.headers)))
        li.setMimeType('application/dash+xml' if self.t == "dash" else "")
        li.setContentLookup(False)
        xbmcplugin.setResolvedUrl(handle, True, li)
