#!/usr/bin/env python
# coding=utf8
#
# This file is part of PlayStream - enigma2 plugin to play video streams from various sources
# Copyright (c) 2016 ivars777 (ivars777@gmail.com)
# Distributed under the GNU GPL v3. For full terms see http://www.gnu.org/licenses/gpl-3.0.en.html
#

import sys,os,re
import urllib2
sys.path.insert(0,os.path.dirname(os.path.abspath(__file__)))
from  sources.SourceBase import stream_type
import util
stream0 = {'name': '', 'url': '', 'quality': '???', 'surl': '', 'subs': '', 'headers': {},"desc":"","img":"","lang":"","type":""}                   

class ContentSources(object):
    """Wrapper for content sources plugin"""

    #----------------------------------------------------------------------
    def __init__(self,plugin_path):
        self.plugins = {}
        self.error_content = [("..atpakaļ","back",None,"Kļūda, atgriezties atpakaļ")]
        sys.path.insert(0, plugin_path)
        for f in os.listdir(plugin_path):
            fname, ext = os.path.splitext(f)
            if fname == "__init__":continue
            if ext == '.py':
                mod = __import__(fname)
                reload(mod)
                if "Source" in dir(mod):
                    self.plugins[fname] = mod.Source()
        sys.path.pop(0)
        cfg = self.plugins["config"]
        for pl in self.plugins.keys():
            found = False
            for lst in cfg.get_lists():
                for item in cfg.lists[lst]:
                    if item[1].split("::")[0]==pl:
                        found = True
                        break
                    if found: break
            if not found:
                title = self.plugins[pl].title if "title" in dir(self.plugins[pl]) else pl
                img = self.plugins[pl].img if "img" in dir(self.plugins[pl]) else ""
                desc = self.plugins[pl].desc if "desc" in dir(self.plugins[pl]) else title
                cfg.add_item("home",(title,"%s::home"%pl,img,desc))
                cfg.write_streams()

    def get_content(self,data):        
        source = data.split("::")[0]
        if source in self.plugins:
            content = self.plugins[source].get_content(data)
            if content:
                if isinstance(content,list):      
                    for i,item in enumerate(content):
                        item2=[]
                        for el in item:
                            if isinstance(el,unicode):
                                el = el.encode("utf8")
                            item2.append(el)
                        content[i]=tuple(item2)
                else:
                    item2=[]
                    for el in content:
                        if isinstance(el,unicode):
                            el = el.encode("utf8")
                        item2.append(el)
                    content=tuple(item2)
                return content
            else:
                return self.error_content
        else:
            return self.error_content

    def get_streams(self,data):
        if stream_type(data):
            if "::" in data:
                data = data.split("::")[1]                    
            content = self.get_content(data)
            stream = stream0.copy()
            stream["name"] = data
            stream["url"] = data
            stream["type"] = stream_type(data)
            #stream["img"] = ""
            #stream["desc"] = ""
            return[stream]

        if not self.is_video(data):
            return []
        source = data.split("::")[0]
        if source in self.plugins:
            streams = self.plugins[source].get_streams(data)
            for s in streams:
                for k in s:
                    if isinstance(s[k],unicode):
                        s[k] = s[k].encode("utf8")            
            return streams
        else:
            return []

    def stream_type(self,data):
        return stream_type(data)

    def is_video(self,data):
        if self.stream_type(data):
            return True
        source = data.split("::")[0]
        if source in self.plugins:
            return self.plugins[source].is_video(data)
        else:
            return False

    def options_read(self,source):
        if source in self.plugins:
            options = self.plugins[source].options_read()
            if options:
                return options
            else:
                return None
        else:
            return None

    def options_write(self,source,options):
        if source in self.plugins:
            return self.plugins[source].options_write(options)
        else:
            return None

if __name__ == "__main__":

    sources = ContentSources("sources")
    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 = sources.get_content(cur[1])

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

        while True:
            a = raw_input("Enter numeber, 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 
        cur2 = content[n-1]

        data0 = cur2[1].split("::")[1] if "::" in cur2[1] else cur2[1]
        if (not data0):
            pass

        elif cur2[1] == "back":
            cur = history.pop()  
        elif sources.is_video(cur2[1]):
            if sources.stream_type(cur2[1]):
                stream = stream0.copy()
                stream["url"] = cur2[1]
                stream["name"] = cur2[0]
                streams = [stream]
            else:
                streams = sources.get_streams(cur2[1])
            if streams:
                util.play_video(streams)
            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
        content = sources.get_content(cur[1])
