#!/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
import requests
import datetime, re, sys,os
import ConfigParser
import ssl
if "_create_unverified_context" in dir(ssl):
    ssl._create_default_https_context = ssl._create_unverified_context

from SourceBase import SourceBase

import resolver
try:
    import util
except:
    sys.path.insert(0,'..')
    import util
from YouTubeVideoUrl import YouTubeVideoUrl

headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
import HTMLParser
h = HTMLParser.HTMLParser()

class Source(SourceBase):

    def __init__(self, country="lv",cfg_path=None):
        self.name = "tvplay"
        self.title = "TVPlay"
        self.img = "tvplay.png"
        self.desc = "tvplay.skaties.lv saturs"
        self.headers = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
""")
        self.headers2 = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
X-Requested-With: XMLHttpRequest
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
""")
        self.url = "http://login.tvplayhome.lt:8081/sb/public/"
        self.kategorijas = [
            ("zinas", "Ziņas un aktualitātes", 33, "tvplay.png", "Ziņas un aktualitātes"),
            ("berniem", "Bērniem", 52, "tvplay.png", "Bērniem"),
            ("seriali", "Seriāli", 38, "tvplay.png", "Seriāli"),
            ("filmas", "Filmas", 72, "tvplay.png", "Filmas"),
            ("izklaide", "Izklaide", 21, "tvplay.png", "Izklaide"),
            ("sovi", "Šovi un raidijumi", 44, "tvplay.png", "Šovi un raidijumi"),
            ("sports", "Sports", 32, "tvplay.png", "Sports"),
            ("rus", "rus.tvplay.lv", 35, "tvplay.png", "Krievu raidijumi"),
        ]

    ######### Entry point ########
    def get_content(self, data):
        print "[lmt] get_content:", data
        source, data, path, plist, clist, params, qs = self.parse_data(data)
        content = []
        content.append(("..return", "back","back.png","Return back"))

        if clist=="home":
            content.extend([
                ("Meklēt", "tvplay::meklet/{0}","tvplay.png","Meklēt"),
                ("Tiešraides", "tvplay::tiesraides","tvplay.png","Tiešraides"),
                ("Jaunākās epizodes", "tvplay::jaunakais/epizodes", "tvplay.png", "Visu kategoriju jaunākie video"),
                ("Jaunākie klipi", "tvplay::jaunakais/klipi", "tvplay.png", "Visu kategoriju jaunākie video"),
                ("Jaunākais pa kategorijām", "tvplay::jaunakais/kategorijas", "tvplay.png", "Jaunākie video pa kategorijām žanru jaunākie video"),
                ("Raidijumi pa kategorijām", "tvplay::raidijumi/kategorijas", "tvplay.png", "Jaunākie video pa kategorijām žanru jaunākie video"),
            ])
            return content

        elif clist in ("meklet"):
            term = plist[1]
            data = "tvplay::asset/search?size=30&page=0&f_title.title=%s&f_country=LV&f_metadata.contentType=EPISODE&f_country=LV" % term
            return self.get_content(data)

        elif clist in ("tiesraides"):
            data = "tvplay::asset/search?size=30&page=0&f_metadata.contentType=LIVE&f_country=LV"
            return self.get_content(data)

        elif clist == "jaunakais":
            if plist[1] == "epizodes":
                data = "tvplay::asset/search?f_title.categories=15004&size=30&page=0&f_metadata.contentType=EPISODE&f_country=LV"
                return self.get_content(data)
            elif plist[1] == "klipi":
                data = "tvplay::asset/search?f_title.categories=15004&size=30&page=0&f_metadata.contentType=CLIP&f_country=LV"
                return self.get_content(data)
            elif plist[1] == "kategorijas":
                for kat in self.kategorijas:
                    content.append(("Jaunākais - "+kat[1], "tvplay::jaunakais/%s" % kat[0], kat[3], kat[4]))
                return content
            elif plist[1] in zip(*self.kategorijas)[0]:
                for k in self.kategorijas:
                    if k[0] == plist[1]:
                        kat_num = k[2]
                        break
                else:
                    return content
                data = "tvplay::asset/search?f_title.categories=%s&size=30&page=0&f_country=LV" % kat_num
                return self.get_content(data)

        elif clist == "raidijumi":
            if plist[1] == "kategorijas":
                for kat in self.kategorijas:
                    content.append(("Raidijumi - "+kat[1], "tvplay::raidijumi/%s" % kat[0], kat[3], kat[4]))
                    #content.append(kat[1], "tvplay::tvSeries/category/id/%s?type=tvseries&size=500&sort=&descending=true" % kat[2], kat[3], kat[4])
                return content
            else:
                for k in self.kategorijas:
                    if k[0] == plist[1]:
                        kat_num = k[2]
                        break
                else:
                    return content
                data = "tvplay::tvSeries/category/id/%s?type=tvseries&size=500&sort=&descending=true&tenantId=2" % kat_num
                return self.get_content(data)

        elif path == "asset/search":
            r = self.call(data)
            if not "content" in r:
                raise Exception("Error reading items list")
            for item in r["content"]:
                data2 = "asset/%s" % item["id"]
                title, img, desc = self.get_title_desc(item)
                content.append((title, self.name+"::"+data2, img, desc))

            if "page" in qs and len(r["content"]) == 30:
                page = int(qs["page"]) + 1
                data2 = re.sub("page=\d+", "page=%s" % page, data)
                content.append(("Next page",self.name+"::"+data2,"next.png","Next page"))
            return content

        elif plist[0] == "tvSeries" and plist[1] == "category":
            r = self.call(data)
            if not "content" in r:
                raise Exception("Error reading items list")
            for item in r["content"]:
                tvseries = True if "type" in qs and qs["type"] == "tvseries" else False
                if tvseries and not "seasonNumber" in item:  # tvseries (programma)
                    #if len(item["seasonIds"]) > 1:
                        #tvseries_id = item["id"]
                    #else:
                       # tvseries_id = item["seasonIds"][0]
                    data2 = "tvSeries/%s" % item["id"]
                    title = item["title"]["title"]
                    img = "http://login.tvplayhome.lt:8081" + item["posterUrl"] if "posterUrl" in item else self.img
                    desc = []
                    if "summaryLong" in  item["title"]:
                        desc.append(item["title"]["summaryLong"])
                    desc = "\n".join(desc)
                    content.append((title, self.name+"::"+data2, img, desc))
            if "page" in qs:
                page = int(qs["page"]) + 1
                data2 = re.sub("page=\d+", "page=%s" % page, data)
                content.append(("Next page",self.name+"::"+data2,"next.png","Next page"))
            return content

        elif plist[0] == "tvSeries":
            item = self.call(data)
            if "seasonIds" in item and len(item["seasonIds"]) > 1:
                title0 = item["title"]["title"] + ". " + "Visi video"
                data2 = "asset/search?f_metadata.tvSeriesId=%s&page=0&size=30" % item["id"]
                img = "http://login.tvplayhome.lt:8081" + item["posterUrl"] if "posterUrl" in item else self.img
                desc = []
                if "summaryShort" in item["title"]:
                    desc.append(item["title"]["summaryShort"])
                if "summaryLong" in item["title"]:
                    desc.append(item["title"]["summaryLong"])
                desc = "\n".join(desc)
                content.append((title0, self.name+"::"+data2, img, desc))
                for season in item["seasonIds"]:
                    data2 = "tvSeries/%s" % season
                    item = self.call(data2)
                    title = item["title"]["title"]
                    img = "http://login.tvplayhome.lt:8081" + item["posterUrl"] if "posterUrl" in item else self.img
                    desc = []
                    if "summaryShort" in item["title"]:
                        desc.append(item["title"]["summaryShort"])
                    if "summaryLong" in item["title"]:
                        desc.append(item["title"]["summaryLong"])
                    desc = "\n".join(desc)
                    content.append((title, self.name+"::"+data2, img, desc))
                return content
            else:
                data1 = item["vodAssetsUrl"].replace("/sb/public/", "")
                data1 += "&size=30&page=0"
                return self.get_content(data1)

        ### kaut kas neparedzets ###
        else:
            return content

    def get_title_desc(self, item):
        title = item["title"]["title"]
        if "titleBrief" in item["title"]:
            title += ". " + item["title"]["titleBrief"]
        img = "http://login.tvplayhome.lt:8081" + item["posterUrl"]
        desc = []
        if "summaryShort" in  item["title"]:
            desc.append(item["title"]["summaryShort"])
        if "summaryLong" in  item["title"] and item["title"]["summaryLong"] <> item["title"]["summaryShort"]:
            desc.append(item["title"]["summaryLong"])
        if "metadata" in item:
            if "contentType" in  item["metadata"]:
                if item["metadata"]["contentType"] == "CLIP":
                    desc.append("Klips")
                    #desc.append(item["metadata"]["contentType"])
            if "seasonNumber" in item["metadata"]:
                desc.append("Season: %s, episode: %s" % (item["metadata"]["seasonNumber"], item["metadata"]["episodeNumber"] if "episodeNumber" in item["metadata"] else ""))
            if "displayRunTime" in item:
                desc.append("Lenght: %s" % item["displayRunTime"])
            if "airDate" in item["metadata"]:
                desc.append("Aired: %s" % item["metadata"]["airDate"])
                dd =  item["metadata"]["airDate"].split("T")[0].split("-")
                title = title + " [%s.%s.%s]" % (dd[2], dd[1], dd[0])
            if "licensingWindowEnd" in item["metadata"]:
                desc.append("Till: %s" %item["metadata"]["licensingWindowEnd"])
        desc = "\n".join(desc)
        return title, img, desc



    def is_video(self,data):
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        if clist == "asset" and re.search("\d+", plist[1]):
            return True
        else:
            return False

    def call(self, data,params=None,headers=None,lang=""):
        if not headers: headers = self.headers
        url = self.url+data
        r = requests.get(url,headers = headers)
        result = json.loads(r.content)
        #result = self._http_request(url,params,headers=headers)
        return result

    def get_streams(self,data):
        print "[tvplay] get_streams:", data
        if not self.is_video(data):
            return []
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        r = self.call(data)
        if not ("movie" in r and "contentUrl" in r["movie"]):
            return []
        data2 = r["movie"]["contentUrl"]
        title, img, desc = self.get_title_desc(r)
        stream = util.item()
        stream["name"] = title
        stream["url"] = data2
        stream["img"] = img
        stream["desc"] = desc
        stream["resolver"] = "tvplay"
        return [stream]


if __name__ == "__main__":
    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"
    if len(sys.argv) > 2:
        run.run_cli(source, data)
    else:
        run.run(source, data)
    sys.exit()
