#!/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 urllib2, urllib
import datetime, re, sys, os
import ssl
if "_create_unverified_context" in dir(ssl):
    ssl._create_default_https_context = ssl._create_unverified_context
try:
    import util
except:
    sys.path.insert(0,'..')
    import util
from SourceBase import SourceBase

headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
re_search = lambda p, s: re.search( p, s, re.DOTALL).group(1).strip() if re.search( p, s, re.DOTALL) else ""
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
""")
import HTMLParser
h = HTMLParser.HTMLParser()

class Source(SourceBase):

    def __init__(self,country="lv",cfg_path=None):
        self.name = "xtv"
        self.title = "XTV.lv"
        self.img = "xtv.png"
        self.desc = "xtv.lv satura skatīšanās (TVRiga24,360TV,STV)"
        self.country=country

    def get_content(self, data):
        print "[xtv] 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([
                ("Jaunākie", "xtv::latest", self.img,"Jaunākie video"),
                ("Populārakie", "xtv::popular",self.img,"Populāraie video"),
                ("Visi raidījumi", "xtv::programs",self.img,"Visi raidījumi"),
                ("Ziņas", "xtv::category/6blmNmLpOPR-zinas/full_show?page=1",self.img,"Ziņu raidījumi un sižeti"),
                ("Diskusijas", "xtv::category/AZoQGEwNX89-diskusijas/full_show?page=1",self.img,"Diskusiju raidījumi un sižeti"),
                ("Izklaide", "xtv::category/gnPBGaJp8or-izklaide/full_show?page=1",self.img,"Izklaides raidījumi un sižeti"),
                ("Sports", "xtv::category/Lymz7BwGXEk-sports/full_show?page=1",self.img,"Sporta raidījumi un sižeti"),
                ("Meklēt", "xtv::search?q={0}",self.img,"Meklēt raidījumus un sižetus"),
             ])
            return content

        ### Saraksti ###
        elif clist in ("latest", "popular", "category", "programs", "search") or plist[1] == "program":
            r = self.call(data)
            for r0 in re.findall(r'<div class="(tvplot|broadcast)">(.+?)</a>\s+</div>\s+</div>', r, re.DOTALL):
                r2 = r0[1]
                title = util.unescape(re_search("<h5>([^<]+)<", r2))
                data2 = re_search('href="/(.+?)"', r2)
                if "/program/" in data2:
                    data2 += "/full_show?page=1"
                img = re_search('src="(.+?)"', r2)
                duration = re_search('<span class="duration">(.+?)</span>', r2)
                when = re_search('<span>([^<]+)</span>', r2)
                category =  re_search('<p>([^<]+)</p>', r2)
                chan = re_search('<img alt="(.+?) logo"', r2) # <img alt="RigaTV24 logo"
                desc = util.unescape(re_search('title="(.*?)"', r2))
                if when or duration:
                    desc += "\n%s %s" % (when, duration)
                if category:
                    desc += "\n%s" % (category)
                if "/video/" in data2:
                    chan = data2.split("/")[0].upper()
                if chan:
                    title = "%s [%s] " % (title, chan)
                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

        ### Meklēt ###
        elif data == "search":
            return content

        else:
            return content


    def is_video(self,data):
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        if len(plist) > 1 and plist[1] == "video":
            return True
        else:
            return False

    def get_streams(self,data):
        print "[xtv] 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)
        # src: "https://video.xtv.lv/files/cc/e5/cce5a0e95dea4404280dabb2a8470f0b/original.mp4", type: "video
        data2 = re_search('src: "([^"]+)", type: "video', r)
        if not data2:
            return []
        title = util.unescape(re_search('"og:title" content="([^"]+)"', r))
        desc = util.unescape(re_search('"description" content="([^"]+)"', r))
        img = re_search('"thumbnailUrl": "([^"]+)"', r) # "thumbnailUrl": "

        stream = util.item()
        stream["name"] = title
        stream["url"] = data2
        stream["img"] = img
        stream["desc"] = desc
        stream["lang"] = "lv"
        stream["resolver"] = "xtv"
        return [stream]

    def call(self, data,headers=headers0,lang=""):
        API_URL = "https://xtv.lv/"
        #if not lang: lang = self.country
        url = API_URL + data
        content = self._http_request(url)
        return content

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"
    run.run(source, data)
    sys.exit()
