# *      Copyright (C) 2011 Libor Zoubek
# *      Modified by ivars777
# *      Based in code from https://github.com/kodi-czsk/script.module.stream.resolver
# *
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# *
# */
# Based in code from https://github.com/kodi-czsk/script.module.stream.resolver

import re
import traceback

import util
import sys,os
#sys.path.insert(0,os.path.dirname(os.path.abspath(__file__)))
server_path = "resolvers"
sys.path.append(os.path.join(os.path.dirname(__file__), server_path))

RESOLVERS = []
util.debug('%s searching for modules' % __name__)

for module in os.listdir(os.path.join(os.path.dirname(__file__), server_path)):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    module = module[:-3]
    #exec 'import %s' % module
    #resolver = eval(module)
    resolver = __import__(module)
    #reload(resolver)
    
    if not hasattr(resolver, 'resolve'):
        continue
    print 'found %s %s' % (resolver, dir(resolver))
    #util.debug('found %s %s' % (resolver, dir(resolver)))
    if not hasattr(resolver, '__priority__'):
        resolver.__priority__ = 0
    RESOLVERS.append(resolver)
    del module
RESOLVERS = sorted(RESOLVERS, key=lambda m: -m.__priority__)

def item():
    stream0 = {'name': '', 'url': '', 'quality': '???', 'surl': '', 'subs': '', 'headers': {},"desc":"","img":"","lang":"","type":"","order":0}            
    return stream0

def resolve(url):
    """
        resolves given url by asking all resolvers

        returns None if no resolver advised to be able to resolve this url
        returns False if resolver did his job, but did not return any value (thus failed)
        returns Array of resolved objects in positive usecase
    """
    url = util.decode_html(url)
    util.info('Resolving ' + url)
    resolver = _get_resolver(url)
    value = None
    if resolver is None:
        return None
    util.info('Using resolver \'%s\'' % str(resolver.__name__));
    value = resolver.resolve(url)
    if value is None:
        return False
    default = item()
    for i in value:
        if 'name' not in i.keys():
            i['name'] = resolver.__name__
        if 'surl' not in i.keys():
            i['surl'] = url
        for key in default.keys():
            if key not in i.keys():
                i[key] = default[key]   
        if "|" in i["url"]:
            headers = i["url"].split("|")[1]
            i["url"]=i["url"].split("|")[0]
            for h in headers.split("&"):
                if "=" in h:
                    i["headers"][h.split("=")[0]] = h.split("=")[1]

    return sorted(value, key=lambda i: i['quality'], reverse=True)


def _get_resolver(url):
    util.debug('Get resolver for ' + url)
    for r in RESOLVERS:
        util.debug('querying %s' % r)
        if r.supports(url):
            return r

def can_resolve(url):
    """ Returns true if we are able to resolve stream by given URL """
    return _get_resolver(url) is not None


if __name__ == "__main__":

    from subprocess import call
    #url = "http://hqq.tv/player/embed_player.php?vid=235238210241210222228241233208212245&autoplay=no"
    #url = "http://hqq.tv/player/embed_player.php?vid=243221241234244238208213206212211231&autoplay=no"
    url = "http://hqq.tv/player/embed_player.php?vid=208231211231207221227243206206221244&autoplay=no"
    #url = "https://openload.co/embed/TMthIdpy4PI/"
    #url = "https://www.youtube.com/watch?v=Tx1K51_F99o"
    #url = "https://www.youtube.com/watch?v=8BkcX7O1890"
    #url = "https://www.youtube.com/watch?v=Se07R8SYsg0"
    #url = "https://kinostok.tv/embed/731f3437e3c53104dd56d04039a0b15a"
    #url = "http://vk.com/video_ext.php?oid=246066565&id=169244575&hash=d430ab0e76c9f7a1&hd=3"
    #url ="https://openload.co/embed/rPMXJYPTkw4/"
    #url = "https://openload.co/embed/bE7WfZ-vz_A/" 
    #url = "https://openload.co/embed/bE7WfZ/" 
    #url = "https://openload.co/embed/OuskaKyC2GU/"
    url = "http://hqq.tv/player/embed_player.php?vid=235238210241210222228241233208212245&autoplay=no"
    url = "https://hqq.tv/player/embed_player.php?vid=235242211228257255206246241253244213194271217261258"
    #url = "https://openload.co/embed/rmNcP-0QopE/"
    #url = "https://openload.co/embed/gpLF6Grzy80/"
    #url = "https://openload.co/embed/oQLXcU1ITAY/"
    #url = "http://hqq.tv/player/embed_player.php?vid=245208228234224222241224221239207212&autoplay=no"
    url = "https://goo.gl/yMTzqf"
    url = "http://cdn.kapnob.ru/video/5e67c8b1ad018ffa/iframe"
    url = "http://kodik.cc/video/10830/4269a802d1a9d9bdc53fe38488d53a52/720p"
    streams = resolve(url)
    if not streams:
        print "No streams found"
        sys.exit()

    for s in streams:
        print s

    print streams[0]["url"] 
    util.play_video(streams)
    ##call([r"c:\Program Files\VideoLAN\VLC\vlc.exe",streams[0]["url"]])
    pass
