#!/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 os.path,re
import collections
from SourceBase import SourceBase

os.path.dirname(os.path.abspath(__file__))
class Source(SourceBase):

    def __init__(self, cfg_file="streams.cfg", cfg_file2=None):
        self.name = "config"
        self.lists = collections.OrderedDict()
        self.titles = {}
        cur_directory = os.path.dirname(__file__)
        self.cfg_path = cur_directory
        self.set_streams_file(cfg_file)
        print "streams_file=", self.streams_file
        try:
            self.read_streams()
        except Exception as e:
            if cfg_file2:
                # Try fallback
                self.set_streams_file(cfg_file2)
                self.read_streams()
            else:
                raise Exception(e.message)

    def set_streams_file(self, cfg_file):
        if not ("/" in cfg_file or "\\" in cfg_file):  # ja tikai faila nosaukums, tad meklē to source folderi
            self.streams_file = os.path.join(self.cfg_path,cfg_file)
        else:
            self.streams_file = cfg_file

    def get_content(self, data):
        print "[config] get_content",data
        self.read_streams()
        if "::" in data:
            data = data.split("::")[1]
        if not data in self.lists:
            return []
        return self.lists[data]

    def is_video(self,data):
        return False

    def read_streams(self):
        if re.search("(https*|ftps*)://.*", self.streams_file):
            import urllib2
            try:
                sf = urllib2.urlopen(self.streams_file, "r")
            except Exception as e:
                raise Exception("Can not open streams file %s" % self.streams_file)
                #print "Warning: can not open streams file %s, callback to default" % self.streams_file
                #self.streams_file = os.path.join(self.cfg_path, "streams.cfg")
                #sf = open(self.streams_file, "r")
        else:
            try:
                sf = open(self.streams_file, "r")
            except Exception as e:
                raise Exception("Can not open streams file %s" % self.streams_file)
        for line in sf:
            r = re.search("^\[(\w+)\]", line)
            if r:
                name = r.group(1)
                self.lists[name] = []
            else:
                if line[0] in ("#"): continue
                items = line.strip().split("|")
                if not items[0]: continue
                if len(items)==1:
                    self.titles[name] = items[0]
                else:
                    if len(items) == 4:
                        items[3] = items[3].replace("\\n","\n")
                    self.lists[name].append(items)
        sf.close()
    def write_streams(self):

        if re.search("ftps*://.*", self.streams_file):
            mode = "ftp"
        elif re.search("https*://.*", self.streams_file):
            mode = "http"
            print "Warning stream_file http upload no yet implemented"
            return
        else:
            mode = "file"

        if mode == "ftp":
            #import tempfile
            #f = tempfile.NamedTemporaryFile("w", delete=False)
            #tmp_file = f.name
            import StringIO
            f = StringIO.StringIO()
        else:  # Parasts fails
            try:
                f = open(self.streams_file, "w")
            except Exception as e:
                raise Exception("Can not open streams file %s" % self.streams_file)

        for l in self.lists.keys():
            f.write("[%s]\n"%l)
            t = self.get_title(l)
            if t<>l:
                f.write("%s\n"%t)
            for item in self.lists[l]:
                f.write("%s|%s|%s|%s\n"%(item[0].replace("\n",""),item[1],item[2],item[3].replace("\n","\\n")))
            f.write("\n")

        if mode == "ftp":
            import ftplib, urlparse
            p = urlparse.urlparse(self.streams_file)
            try:
                ftp = ftplib.FTP(p.hostname)
                ftp.login(p.username, p.password)
                f.seek(0)
                ftp.storbinary("STOR "+p.path, f)
                ftp.close()
            except Exception as e:
                print e.message
        else:
            f.close()

    def get_lists(self):
        return self.lists.keys()

    def get_list_items(self,name):
        return self.lists[name]

    def get_title(self,name):
        if name in self.titles:
            return self.titles[name]
        else:
            return name

    def add_list(self,name):
        if not name in self.lists.keys():
            self.lists[name] = []

    def del_list(self,name):
        if name in self.lists.keys():
            del self.lists[name]

    def add_item(self,name,item,pos=None):
        if name in self.lists.keys():
            if pos==None:
                self.lists[name].append(item)
            else:
                self.lists[name].insert(pos,item)

    def del_item(self, name, pos):
        self.lists[name].pop(pos)

    def replace_item(self, name, item, pos):
        self.lists[name][pos]=item

    def move_item(self, name, pos, pos2):
        # l.insert(newindex, l.pop(oldindex))
        if pos2 == None:
            self.lists[name].append(self.lists[name].pop(pos))
        elif pos2 < pos:
            self.lists[name].insert(pos2, self.lists[name].pop(pos))
        elif pos2 > pos:
            self.lists[name].insert(pos2-1, self.lists[name].pop(pos))

if __name__ == "__main__":

    source = Source(cfg_file="streams.cfg")
    source.read_streams()
    source.write_streams()
    import sys
    sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
    import run
    source = Source()
    data= sys.argv[1] if len(sys.argv)>1 else source.name+"::home"
    run.run(source, data)
    sys.exit()

    #c.del_item("home",0)
    #c.del_list("favorites")

    #c.add_item("home",("My Streams","config::favorites","","Mani saglabātie TV kanāli un video"),0)
    #c.replace_item("home",("My Streams","config::my_streams","default","Mani saglabātie TV kanāli un video"),0)
    #c.add_list("favorites")
    #c.add_item("favorites",("..return","back","back.png","Atgriezties atpakaļ"))
    #c.add_item("favorites",("LTV1","http://streamltv.cloudy.services/ltv/LTV02.smil/playlist.m3u8","picons/latvia1.png", "Latvijas televīzijas 1.kanāls"))

    #c.write_streams()
    #for item in content: print item

