#!/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
from SourceBase import SourceBase

API_URL = 'http://replay.lsm.lv/'
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
""")
import HTMLParser
h = HTMLParser.HTMLParser()
    
class Source(SourceBase):
    
    def __init__(self,country="lv"):
        self.name = "play24"
        self.title = "Play24.lv"
        self.img = "http://play24.lv/images/play24-logo-black.png"
        self.desc = "play24.lv (Riga24TV) satura skatīšanās"
        
        self.country=country
        
    def get_content(self, data):
        print "[play24] get_content:", data
        if "::" in data:
            data = data.split("::")[1] 
        path = data.split("?")[0]
        clist = path.split("/")[0]
        params = data[data.find("?"):] if "?" in data else ""
        qs = dict(map(lambda x:x.split("="),re.findall("\w+=\w+",params)))
        lang = qs["lang"] if "lang" in qs else self.country
    
        content=[]
        content.append(("..return", "back","","Return back"))
        
        if clist=="home":
            content.extend([
                ("Live stream", "play24::tiesraide","","TV live streams"),
                ("Last videos", "play24::jaunakie","","Last videos"),
                ("Categories", "play24::kategorijas","","Categories"),
                ("Programs", "play24::raidijumi","","Programs"),             
             ])
            return content
  
        ### Jaunākie video ###
        elif clist=="jaunakie":
            url = "http://play24.lv/"
            r = self._http_request(url)
            for item in re.findall(' <div class="top-article__image">.*?<a class="top-article__image-link" href="([^"]+)">.*?<img.+?src="([^"]+)".+?alt="([^"]+)" />.+?</picture>', r, re.DOTALL):
                title = item[2]
                title =  h.unescape(title.decode("utf8")).encode("utf8")
                img = item[1]
                data2 = item[0].replace("http://play24.lv/","")
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))
            return content
                
        ### Kategorijas ###
        elif clist=="kategorijas":
            url = "http://play24.lv/"
            r = self._http_request(url)
            r2 = r[r.find('<div class="footer-navigation">'):]
            for item in re.findall('<a href="http://play24.lv/(kategorija/[^"]+)" class="navigation__link">([^<]+)</a>', r2, re.DOTALL):
                title = item[1]
                data2 = item[0]
                img = ""
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))
            return content
       
        elif clist=="kategorija":
            url = "http://play24.lv/"+data
            r = self._http_request(url)
            for article in re.findall(r"<article\b[^>]*>(.+?)</article>", r, re.DOTALL):
                m = re.search('<a class="masonry-item__link" href="http://play24\.lv/([^"]+)">', article, re.DOTALL)
                data2 = m.group(1) if m else ""
                m = re.search('<img src="([^"]+)" alt="([^"]+)" />', article, re.DOTALL)
                if m:
                    img = m.group(1)
                    title = m.group(2)
                    title =  h.unescape(title.decode("utf8")).encode("utf8")
                else:
                    img = ""
                    title = ""
                m = re.search(r'<span class="masonry-item__tags">\s+<a href="([^"]+)">([^<]+)</a>.*?</span>', article, re.DOTALL)
                progr = m.group(2) if m else ""
                m = re.search('<span class="masonry-item__date">([^<]+)</span>', article, re.DOTALL)
                date = m.group(1).strip() if m else ""
                         
                if date:
                    title = title + " (%s %s)"%(date,progr)
                desc = title + "\n%s - %s"%(progr,date)
                content.append((title,self.name+"::"+data2,img,desc))
            m = re.search(r'<li><a href="http://play24\.lv/([^"]+)" rel="next">&raquo;</a></li>', r, re.DOTALL)
            if m:
                data2 = m.group(1)
                content.append(("Next page",self.name+"::"+data2,"","Next page"))                                            
            return content
        
        ### Raidijumi (programmas)
        elif clist=="raidijumi":
            url = "http://play24.lv/"
            r = self._http_request(url)
            for item in re.findall(r'<li class="tag-box__item">.*?<a href="http://play24\.lv/(birka/[^"]+)">([^<]+)</a>.*?</li>', r, re.DOTALL):
                title = item[1]
                title =  h.unescape(title.decode("utf8")).encode("utf8")
                data2 = item[0]
                img = ""
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        ### Programmas (video saraksts)
        elif clist=="birka":
            url = "http://play24.lv/"+data
            r = self._http_request(url)
            for item in re.findall(r'<article\b[^>]*>.+?<a class="masonry-item__link" href="http://play24.lv/([^"]+)">.*?<img src="([^"]+)" alt="([^"]+)" />.*?<span class="masonry-item__tags">.+?<a href="([^"]+)">([^<]+)</a>.*?<span class="masonry-item__date">([^<]+)</span>.*?</article>', r, re.DOTALL):
                title = item[2]
                title =  h.unescape(title.decode("utf8")).encode("utf8")
                title = title + " (%s)"%item[5].strip()
                img = item[1]
                data2 = item[0]
                desc = title + "\n%s - %s"%(item[4],item[5].strip())
                content.append((title,self.name+"::"+data2,img,desc))
            m = re.search(r'<li><a href="http://play24\.lv/([^"]+)" rel="next">&raquo;</a></li>', r, re.DOTALL)
            if m:
                data2 = m.group(1)
                content.append(("Next page",self.name+"::"+data2,"","Next page"))                                            
            return content

        elif clist == "video" or clist == "tiesraide":
            if clist == "video":  
                url = "http://play24.lv/"+data
                r = self._http_request(url)
                # var ov_video_id = '59422';
                m = re.search(r"var ov_video_id = '(\d+)';", r, re.DOTALL)
                if m:
                    id = m.group(1)
                else:
                    return ("No stream found %s"%data,"","","No stream found")
                m = re.search('<meta name="description" content="([^"]+)" />', r, re.DOTALL)
                desc = m.group(1) if m else ""
                desc = h.unescape(desc.decode("utf8")).encode("utf8")
                
                url = "http://player.tvnet.lv/v/%s"%id
            else:
                url = "http://player.tvnet.lv/l/11"
                desc = ""
            r = self._http_request(url)
            m = re.search('<h1 class="static title">.+?<a href="[^"]+">([^<]+)</a>', r, re.DOTALL)
            title = m.group(1) if m else ""   
            s = {}
            for item in re.findall('source src="([^"]+)" data-stream="([^"]+)" data-quality="([^"]+)"', r, re.DOTALL):
                s[item[1]] = (item[0],item[2])
            data2 = ""
            for t in ("hls","http","rtmp"):
                if t in s:
                    data2 = s[t][0]
                    break
            return (title,data2,"",desc)
               
    
    def is_video(self,data):
        if "::" in data:
            data = data.split("::")[1]
        cmd = data.split("/")
        if cmd[0] in ("video","tiesraide"):
            return True
        else:
            return False
    
    def call(self, data,headers=headers0,lang=""):
        if not lang: lang = self.country
        url = API_URL%lang + data
        #print "[TVPlay Api] url: ",url
        result = []
        content = self._http_request(url)
        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