# -*- coding: UTF-8 -*-

import re,os,sys
import json
try:
    import util
except:
    pp = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0,os.sep.join(pp.split(os.sep)[:-1]))
    import util
import urllib2
import requests
try:
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except:
    pass
#from aadecode import AADecoder

__author__ = 'ivars777'
__name__ = 'cloudsany' if __name__ <> "__main__" else __name__


def supports(url):
    # https://cloudsany.com/i/b4kt66gm2sw4
    return re.search(r'cloudsany\.\w+/\w/.+', url) is not None


#INFO_URL = API_BASE_URL + '/streaming/info'

def resolve(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
        'Accept-Encoding': 'none',
        'Accept-Language': 'en-US,en;q=0.8',
        'Referer': url}  # 'Connection': 'keep-alive'

    # https://cloudsany.com/i/b4kt66gm2sw4
    m = re.search('cloudsany\.\w+/i/(\w+)', url)
    if not m:
        return stream
    vid = str(m.group(1))

    r = requests.get(url, headers=headers)
    if r.status_code <> 200:
        raise Exception("Error getting stream")
    r = r.content
    m = re.search(r"'(https\|.+?jwplayer)'", r)
    if not m:
        print url
        if "File was deleted" in r:
            raise Exception("File was deleted")
        else:
            raise Exception("Can not find stream")

    p = m.group(1).split("|")
    p0 = m.group(1)


    # Subtitles #
    subs = []
    # https://cloudsany.com/subtitles/0w3y7su4c2ko.srt
    # Latvian|label|srt|subtitles
    #url_sub = "https://cloudsany.com/subtitles/%s.%s" % (vid, "srt")
    url_sub = "https://cloudsany.com/subtitles/%s.srt" % vid
    r2 = requests.head(url_sub)
    m = re.search(r"(\w+)\|label\|(\w+)\|(\w+)\|subtitles", p0)
    if r2.status_code == 200 and m:
        sub = {}
        #url_sub = "https://cloudsany.com/subtitles/%s.%s" % (vid, "srt")
        url_title = m.group(1)
        print url_title
        sub["url"] = url_sub
        sub["lang"] = m.group(1)
        sub["name"] = m.group(1)
        sub["type"] = m.group(2)
        subs = [sub]

    # Stream URL
    # co|sanii|dl1|file
    m1 = re.search("\|(co)\|(\w*)\|(\w*)\|(\w*)\|", p0)
    # tracks|mp4|video|ut4dluxu56tyll|files
    m2 = re.search(r"tracks\|(\w+)\|(\w+)\|(\w+)\|files", p0)
    # 0://c.b.a/1t/6/1s/1r.1q
    m3 = re.search(r"0://\w+\.\w+\.\w+/\w+/(\d+)/", r)
    if not (m1 and m2 and m3):
        raise Exception("Can not find stream url")
    # https://dl1.sanii.co/files/6/ut4dluxu56tyll/video.mp4
    l1 = list(m1.groups())
    if "" in l1: l1.remove("")
    url = "https://%s.%s.%s/files/%s/%s/%s.%s" % (
        l1[2], l1[1], l1[0], m3.group(1), m2.group(3), m2.group(2), m2.group(1))
    print url

    s = util.item()
    s["url"] = url
    s["type"] = util.stream_type(s["url"])
    s["resolver"] = __name__
    #s["lang"] = lang
    s["subs"] = subs
    s["name"] = url
    return [s]


if __name__ == "__main__":

    from subprocess import call
    url = "https://cloudsany.com/i/b4kt66gm2sw4"
    url = "https://cloudsany.com/i/jqfm2sqwar22"  # teorija par visu/SUB
    streams = resolve(url)
    if not streams:
        print "No streams found"
        sys.exit()

    for s in streams:
        print s
    from run import player
    player(streams[0]["url"])
    #print streams[0]["url"]
    #call([r"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe",streams[0]["url"]])
    pass
