#!/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 glob, traceback
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sources.SourceBase import stream_type
import util

show_hidden = False  # Ja True, tad vienalga radā hidden sources (noder izstradē)

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

    #----------------------------------------------------------------------
    def __init__(self, plugin_path, cfg_file="streams.cfg", cfg_file2=None):
        self.plugins = {}
        self.error_content = [("..atpakaļ", "back", "back.png", "Kļūda, atgriezties atpakaļ")]
        sys.path.insert(0, plugin_path)
        #for f in os.listdir(plugin_path):
        #for f in next(os.walk(plugin_path))[2]:
        print "ContentSources: Importing sources from "+plugin_path
        files = glob.glob(os.path.join(plugin_path, "*.py"))
        for f in files:
            fname, ext = os.path.splitext(f)
            fname = os.path.split(fname)[1]
            if fname == "__init__": continue
            if ext == '.py':
                print "Importing %s"%fname
                mod = __import__(fname)
                reload(mod)
                if "Source" in dir(mod):
                    if mod.__name__ == "config":
                        self.plugins[fname] = mod.Source(cfg_file=cfg_file)
                    else:
                        self.plugins[fname] = mod.Source()
                    print fname+ " imported"
                else:
                    pass
                    #print fname+ "skipped"
        sys.path.pop(0)
        if not "config" in self.plugins:
            raise Exception("Problem importing content sources")
        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, qs=None):
        source = data.split("::")[0]
        if source in self.plugins:
            content0 = self.plugins[source].get_content(data)
            if content0:
                content = []
                if isinstance(content0,list):
                    for i,item in enumerate(content0):
                        source2 = item[1].split("::")[0]
                        if not (source2 == "back" or item[1].startswith("http") or item[1].startswith("rtmp")):
                            if source2 not in self.plugins or (not show_hidden and "hidden" in dir(self.plugins[source2]) and self.plugins[source2].hidden):
                                continue
                        item2=[]
                        for el in item:
                            if isinstance(el,unicode):
                                el = el.encode("utf8")
                            el = util.unescape(el)
                            item2.append(el)
                        content.append(tuple(item2))
                else:
                    item2=[]
                    for el in content0:
                        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, qs=None):
        if stream_type(data):
            if "::" in data:
                data = data.split("::")[1]
            content = self.get_content(data)
            stream = util.item()
            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")
                if not "resolver" in s:
                    s["resolver"] = source
                if not "surl" in s or not s["surl"]:
                    s["surl"] = data
                if not "nfo" in s:
                    s["nfo"]={"movie":{"title":s["name"],"thumb":s["img"],"plot":s["desc"]}}
            return streams
        else:
            return []

    def get_info(self,data, qs=None):
        nfo = {}
        if self.is_video(data):
            source = data.split("::")[0]
            if source in self.plugins:
                if "get_info" in dir(self.plugins[source]):
                    nfo = self.plugins[source].get_info(data)
                else:
                    streams = self.get_streams(data)
                    if streams and "nfo" in streams[0] and streams[0]["nfo"]:
                        nfo = streams[0]["nfo"]
                    else:
                        nfo = {"movie": {"title": current[0], "thumb": self.current[2], "plot": self.current[3]}}



        else:
            pass    # TODO create nfo for listing
        return nfo


    def stream_type(self,data, qs=None):
        return stream_type(data)

    def is_video(self,data, qs=None):
        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, qs=None):
        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, qs=None):
        if source in self.plugins:
            return self.plugins[source].options_write(options)
        else:
            return None

if __name__ == "__main__":
    from run import run
    show_hidden = False
    data= sys.argv[1] if len(sys.argv) > 1 else "config::home"
    cfg_file = sys.argv[2] if len(sys.argv) > 2 else "streams.cfg"
    sources = ContentSources("sources", cfg_file=cfg_file)
    run(sources, data)
