#!/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
#


try:
    import json
except:
    import simplejson as json
#!/usr/bin/env python
# coding=utf8
import urllib2, urllib
import datetime, re, sys
from SourceBase import SourceBase

API_URL = 'http://playapi.mtgx.tv/v3/'
headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
headers0 = headers2dict("""
User-Agent: Mozilla/5.0 (Linux; U; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
""")

REGIONS = [
    ("Latvia",None,"lv",""),
    ("Estonia",None,"ee",""),
    ("Lituania",None,"lt",""),
    ("Sweden",None,"se",""),
    ("Denmark",None,"dk",""),
    ("Norway",None,"no",""),
    ("Bulgaria",None,"bg","")
]


class Source(SourceBase):
    
    def __init__(self,country="lv"):
        self.name = "mtgplay"
        self.title = "Skaties.lv (TV3)"
        self.img = "http://skaties.lv/touch-icon-192x192.png"
        self.desc = "MTG skaties.lv satura skatīšanās (LNT,TV3, TV6 u.c.)"
        
        self.country=country
        self.pic_size = "327x250" #"1000x765"
        
    def get_content(self, data):
        print "[mtgplay] get_content:", data
        if "::" in data:
            data = data.split("::")[1]        
        if "/" in data:
            citem,cid = data.split("/")
            clist = ""
        else:
            clist = data.split("?")[0]
            qs = dict(map(lambda x:x.split("="),re.findall("\w+=\w+",data)))
            citem,cid = ("","")
            self.country = qs["country"] if "country" in qs else "lv"
        
        content=[]
        content.append(("..return", "back","","Return back"))
        
        if clist=="home":
            content.extend([
                #("Search", "mtgplay::meklet?country=%s&term={0}"%self.country,"","Search videos"), ### TODO                
                ("TV Live", "mtgplay::videos?country=%s&order=title&type=live"%self.country,"","TV live streams(not always available)"),
                ("Last videos", "mtgplay::videos?country=%s&order=-airdate"%self.country,"","Last aired videos"),
                ("Categories", "mtgplay::categories?country=%s&order=name"%self.country,"","Categories"),
                ("Channels", "mtgplay::channels?country=%s&order=id"%self.country,"","TV channels"),
                ("Programs by name", "mtgplay::formats?country=%s&order=-title"%self.country,"","Programs by name"),             
                ("Programs by popularity", "mtgplay::formats?country=%s&order=-popularity"%self.country,"","Programs by popularity")             
            ])
            return content
        
        r = self.call(data)
        if not r:
            content.append(("Error", "","","Error reading '%s'"%data))
            return content
        
        if clist:
            if r["_links"].has_key("prev"):
                data2 = r["_links"]["prev"]["href"].replace(API_URL,"")
                content.append(("Previous page", self.name+"::"+data2.encode("utf8"),"", "Goto previous page"))
                
            if "_embedded" in r:
                for item in r["_embedded"][clist]:
                    if "title" in item:
                        title = item["title"]
                    elif "name" in item:
                        title = item["name"]
                    #data2 = self.name+"::"+"%s/%s"%(clist,item["id"]) 
                    img = item["_links"]["image"]["href"].replace("{size}",self.pic_size) if "image" in item["_links"] else ""
                    desc = item["summary"] if "summary" in item and item["summary"] else ""
                    
                    ### Video ###
                    if clist=="videos":
                        data2 = "videos/%s"%item["id"]                            
                        summary = item["summary"] if item["summary"] else ""
                        air_at = item["broadcasts"][0]["air_at"] if "broadcasts" in item and len(item["broadcasts"])>0 and "air_at" in item["broadcasts"][0] else ""
                        if not air_at:
                            air_at = item["publish_at"] if "publish_at" in item else ""
                        air_at = air_at[0:16].replace("T"," ") if air_at else ""
                        try: playable_to = item["broadcasts"][0]["playable_to"]
                        except: playable_to =""
                        playable_to = "(till "+playable_to[0:10].replace("T"," ")+")" if playable_to else ""
                        duration = item["duration"] if "duration" in item else ""
                        duration = str(datetime.timedelta(seconds=int(duration))) if duration else ""
                        try:
                            views = item["views"]["total"] if "views" in item and "total" in item["views"] else ""
                            views = views+" views"
                        except: views = ""
                        desc = "Aired: %s %s\nDuration: %s %s\n\n%s"%(air_at, playable_to,duration,views,summary)
                        
                    ### Categories ###     
                    elif clist == "categories":
                        #data2 = item["_links"]["formats"]["href"].replace(API_URL,"")
                        data2 = "formats?category=%s"%item["id"]
                        if "country" in qs: data2 += "&country="+qs["country"]
                        if "category" in qs: data2 += "&category="+qs["category"]
                        if "channel" in qs: data2 += "&channel="+qs["channel"]
                        data2 += "&order=title"
                        
                    ### Channels ###     
                    elif clist == "channels":
                        #data2 = item["_links"]["categories"]["href"].replace(API_URL,"")
                        data2 = "categories?channel=%s"%item["id"]
                        if "country" in qs: data2 += "&country="+qs["country"]
                        if "category" in qs: data2 += "&category="+qs["category"]
                        if "channel" in qs: data2 += "&channel="+qs["channel"]
                        data2 += "&order=name"
                        
                    ### Formats (programs) ###     
                    elif clist == "formats":
                        #data2 = item["_links"]["videos"]["href"].replace(API_URL,"")
                        data2 = "seasons?format=%s"%item["id"]
                        #if "country" in qs: data2 += "&country="+qs["country"]
                        #if "category" in qs: data2 += "&category="+qs["category"]
                        #if "channel" in qs: data2 += "&channel="+qs["channel"]
                        data2 += "&order=title"
                        air_at = item["latest_video"]["publish_at"] if "publish_at" in item["latest_video"] else ""
                        air_at = air_at[0:16].replace("T"," ") if air_at else ""
                        if air_at:
                            desc = "Last video: %s\n"%air_at + desc                        
                        
                    ### Seasons ###     
                    elif clist == "seasons":
                        #data2 = item["_links"]["videos"]["href"].replace(API_URL,"")
                        data2 = "videos?season=%s"%item["id"]
                        #if "country" in qs: data2 += "&country="+qs["country"]
                        #if "category" in qs: data2 += "&category="+qs["category"]
                        #if "channel" in qs: data2 += "&channel="+qs["channel"]
                        data2 += "&order=title"
                        
                        summary = item["summary"] if "summary" in item and item["summary"] else ""
                        try:
                            latest_video = item["latest_video"]["publish_at"]
                            latest_video = latest_video[0:16].replace("T"," ")
                        except: latest_video = ""
                        desc = ("%s\nLatest video: %s"%(summary,latest_video))
                                      
                    content.append((title.encode("utf8"),self.name+"::"+data2.encode("utf8"),img.encode("utf8"),desc.encode("utf8")))
                    
            if r["_links"].has_key("next"):
                data2 = r["_links"]["next"]["href"].replace(API_URL,"").encode("utf8")
                content.append(("Next page", self.name+"::"+data2.encode("utf8"),"","Goto next page"))
                
        elif citem:
            item = r
            if "title" in item:
                title = item["title"]
            elif "name" in item:
                title = r["name"]
            #data2 = self.name+"::"+"%s/%s"%(clist,item["id"]) 
            img = item["_links"]["image"]["href"].replace("{size}",self.pic_size) if "image" in item["_links"] else ""
            desc = item["summary"] if "summary" in item and item["summary"] else ""
            
            dd = "videos/stream/%s"%cid
            r2 = self.call(dd)
            if "streams" in r2 and "hls" in r2["streams"]:
                data2 = r2["streams"]["hls"]
                content = (title.encode("utf8"),data2.encode("utf8"),img.encode("utf8"),desc.encode("utf8"))
            elif "msg" in r2:
                content = (r2["msg"].encode("utf8"),"","","")
            else: 
                content = ("Error getting stream","","","")            
            
        else:
            pass
        return content
    
    def is_video(self,data):
        if "::" in data:
            data = data.split("::")[1]
        cmd = data.split("/")
        if cmd[0]=="videos":
            return True
        else:
            return False
    
    def get_stream(self,id):   
        dd = "videos/stream/%s"%id
        r2 = self.call(dd)
        if "streams" in r2 and "hls" in r2["streams"]:
            data2 = r2["streams"]["hls"]
        else:
            data2 = ""
        return data2.encode("utf8")
        
    def call_all(self, endpoint, params = None):
        url = API_URL % (endpoint)
        if params:
            url += '?' + params
        print "[TVPlay Api] url: ",url
        result = []
        while True:
            content = self._http_request(url)
            if content:
                try:
                    content = json.loads(content)
                except Exception, ex:
                    return {" Error " : "in call_api: %s" % ex}
            else: break
            if content.has_key("_embedded") and content["_embedded"].has_key(endpoint):
                result.extend(content["_embedded"][endpoint])
                pass
            else: break
            if content.has_key("_links") and content["_links"].has_key("next"):
                url = content["_links"]["next"]["href"]
            else: break
        return result
    
    def call(self, data,headers=headers0):
        url = API_URL + data
        #print "[TVPlay Api] url: ",url
        result = []
        content = self._http_request(url)
        if content:
            try:
                result = json.loads(content)
            except Exception, ex:
                return None
        return result

    def _http_request0(self, url,headers=headers0):
        try:
            r = urllib2.Request(url, headers=headers)
            u = urllib2.urlopen(r)
            content = u.read()
            u.close()
            return content
        except Exception as ex:
            if "read" in ex:
                content = ex.read()
            else:
                content = None
            return content

if __name__ == "__main__":
    country= "lv"
    c = Source(country)
    if len(sys.argv)>1:
        data= sys.argv[1]
    else:
        data = "home"
    content = c.get_content(data)
    for item in content:
        print item
    #cat = api.get_categories(country)
    #chan = api.get_channels("lv")
    #prog = api.get_programs(channel=6400)
    #prog = api.get_programs(category=55)
    #seas = api.get_seasons(program=6453)
    #str = api.get_streams(660243)
    #res = api.get_videos(802)
    #formats = api.getAllFormats()
    #det = api.detailed("1516")
    #vid = api.getVideos("13170")
    pass