import os, re, sys, traceback, urllib

from plex_test_case import PlexTestCase, PlexCall
from Framework.api.objectkit import ObjectContainer
from content.util import stream_type
import syspath
#for f in syspath.folders:

def get_content(data, title="Title"):
    if not data.startswith("search"):
        data = data.replace("/", "%2F")
        data = urllib.quote(data)
        status, headers, body = t.request(u'/video/playstream/%s?title=%s' % (data, title))
    else:  # Search object
        query = raw_input("Search: ")
        data = data.format(query)
        status, headers, body = t.request(u'/video/playstream/%s&query=%s' % (data, query))
    #print body
    #result = re.findall('title="([^"]+)"\s+thumb="([^"]+)"\s+key="([^"]+)"\s+summary="([^"]+)"', body)
    result =  re.findall('<(\w+)\s(.+?)/>', body)
    result2 = []
    for item0 in result:
        item_type = item0[0]
        data2 = re.search('key="(.+?)"', item0[1]).group(1) if re.search('key="(.+?)"',item0[1]) else ""
        data2 = data2.replace("/video/playstream/", "")
        if not data2.startswith("search"):
            data2 = data2.split("?")[0]
            data2 = urllib.unquote(data2)
            data2 = data2.replace("%2F", "/")
        title = re.search('title="(.+?)"', item0[1]).group(1) if re.search('title="(.+?)"',item0[1]) else ""
        desc = re.search('summary="(.+?)"', item0[1]).group(1) if re.search('summary="(.+?)"',item0[1]) else ""
        result2.append((title, data2, "", desc, item_type))
    return result2

def get_streams(data, title="Title"):
    data = data.replace("/", "%2F")
    data = urllib.quote(data)
    status, headers, body = t.request(u'/video/playstream/%s?title=%s' % (data, title))
    print body
    #TODO
    return []


# os.environ["PLEXBUNDLEDPLUGINSPATH"] = r"C:\Data\Programming\Plex"
os.environ["PLEXLOCALAPPDATA"] = r"C:\Data\Programming\Plex"
t = PlexCall()
#for item in get_content("config::home", "Home"):
#    print item


if len(sys.argv)>1:
    data= sys.argv[1]
else:
    data = "config::home"

#options = sources.options_read("ltc")
#print options
history = []
cur = ("Home",data,None,None)
content = get_content(cur[1])

exit_loop = False
while True:
    print "\n======================================================="
    print "data= ", cur[1]
    print "======================================================="
    for i,item in enumerate(content):
        s = "%i: %s - %s %s"%(i,item[0],item[1],item[2])
        print s #.encode(sys.stdout.encoding,"replace")

    while True:
        a = raw_input("Enter number, (-) for download, q for exit: ")
        if a in ("q","Q","x","X"):
            exit_loop = True
            print "Exiting"
            break
        try:
            n = int(a)
            break
        except:
            print "Not number!"
    if exit_loop: break
    download = False
    if n<0:
        n = abs(n)
        download = True
    cur2 = content[n]
    data0 = cur2[1].split("::")[1] if "::" in cur2[1] else cur2[1]
    if not data0:
        pass
#    elif cur2[1] == "back":
#        cur = history.pop()
    elif cur2[4] == "Video":  #is_video(cur2[1]):
        if stream_type(cur2[1]):
            stream = util.item()
            stream["url"] = cur2[1]
            stream["name"] = cur2[0]
            streams = [stream]
        else:
            try:
                if not download:
                    streams = get_streams(cur2[1])
                else:
                    stream = util.item()
                    stream["url"] = cur2[1]
                    stream["name"] = cur2[0]
                    stream["url"] = util.streamproxy_encode2(stream["url"])
                    print stream["url"]
                    streams = [stream]
            except Exception as e:
                print unicode(e)
                traceback.print_exc()
                streams = []
        if streams:
            if not download:
                util.play_video(streams)
            else:
                #urlp = util.streamproxy_encode2(streams[0]["url"])
                #print urlp
                #util.player(urlp)
                #Downloader.download_video(streams)
                pass
        else:
            print "**No stream to play - %s "%(
                cur2[1])
            raw_input("Press any key")
        #import os
        #os.system('"c:\Program Files (x86)\VideoLAN\VLC\vlc.exe" "%s"'%cur2[1])

    else:
        if "{0}" in cur2[1]:
            a = raw_input("Enter value:")
            cur2 = (cur2[0],cur2[1].format(a),cur2[2],cur2[3])
        history.append(cur)
        cur = cur2
    try:
        # Regular item
        content = get_content(cur[1])
    except Exception as e:
        print unicode(e)
        traceback.print_exc()
        raw_input("Continue?")

