#!/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="",cfg_path=None):
        self.name = "lmt"
        self.title = "LMT straume"
        self.img = "lmt.png"
        self.desc = "LMT straume - dažādi video latviesu valodā"
        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://straume.lmt.lv/lv/"

    ######### 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", "lmt::meklet?q={0}","","Meklēt"),
                ("Straumes", "lmt::straumes","","Tiešraides un aktuāli video"),
                #("TV", "lmt::tv","","TV tiešraides (tikai LMT tīklā)"),
                ("Jaunākie", "lmt::video/jaunakie?videoPage=1", "", "Visu žanru jaunākie video"),
                ("Sports", "lmt::video/sports?videoPage=1", "", "Sports"),
                ("Kultūra un māksla", "lmt::video/kultura?videoPage=1", "", "Kultūra un māksla"),
                ("Konferences", "lmt::video/konferences?videoPage=1", "", "Konferences"),
                ("Raidījumi", "lmt::video/raidijumi?videoPage=1", "", "Raidījumi"),
                ("Notikumi", "lmt::video/notikumi?videoPage=1", "", "Notikumi"),
                ("Filmas un seriāli", "lmt::video/filmas?videoPage=1", "", "Filmas un seriāli"),
                ("Dažādi video", "lmt::video/dazadi?videoPage=1", "", "Dažādi video"),
                ("Viedtelevīzija", "lmt::video/viedtelevizija?videoPage=1", "", "Viedtelevīzija"),
            ])
            return content

        elif clist in ("meklet","video", "straumes","video-saraksts"):
            r=self.call(data)
            result = re.findall('<a class="video-picture" (.+?)</li>', r, re.IGNORECASE | re.MULTILINE)
            for r2 in result:
                m = re.search('<a class="video-title" href="/lv/([^"]+)">([^<]+)<', r2)
                title = m.group(2)
                data2 = m.group(1)
                m = re.search("([^ ]+) 2x", r2)
                if m:
                    img = m.group(1)
                else:
                    m = re.search('<img src="([^"]+)', r2)
                    img = m.group(1) if m else ""
                if img.startswith("//"):
                    img = "http:" + img
                m = re.search('<span class="playlist-overlay">([^<]+)</span>', r2)
                overlay = m.group(1) if m else ""
                m = re.search('<span class="badge badge-[^>]+>([^<]+)(<[^>]+>([^<]+))*</span>', r2, re.IGNORECASE)
                badge = ""
                if m:
                    badge = m.group(1)
                    if m.group(3):
                        badge = badge + m.group(3)
                categories = re.findall('<span class="category-title">([^<]+)</span>', r2)
                categories = "".join(categories)
                if overlay:
                    title = "%s [%s]"%(title,overlay)
                if badge:
                    title = "%s [%s]"%(title,badge)
                desc = title
                if categories:
                    desc = desc + "\n"+ categories
                content.append((title,self.name+"::"+data2,img,desc))
            m = re.search("videoPage=(\d+)",data)
            if m:
                page = int(m.group(1))+1
                data2 = re.sub(r"videoPage=\d+", r"videoPage=%s"%page, data)
                content.append(("Next page",self.name+"::"+data2,"next.png","Next page"))
            #print content
            return content


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

    def is_video(self,data):
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        if not clist in ("meklet","video", "straumes","video-saraksts","home"):
            return True

    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)
        return r.content
        #result = self._http_request(url,params,headers=headers)
        return result

    def get_streams(self,data):
        print "[lmt] get_streams:", data
        if not self.is_video(data):
            return []
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        r = self.call(path)
        title = re.search("<h1>(.+?)</h1", r, re.IGNORECASE).group(1)
        m = re.search('<a class="category-title".+?[^>]+>([^<]+)<', r, re.IGNORECASE | re.DOTALL)
        categories = m.group(1) if m else ""
        m = re.search('<span class="category-title">([^<]+)</span>.+?</p>', r, re.IGNORECASE | re.DOTALL)
        if m:
            categories = categories + m.group(1)
        if categories:
            tite = "%s [%s]"%(title,categories)
        img = re.search('<meta property="twitter:image" content="([^"]+)">', r, re.IGNORECASE | re.DOTALL).group(1)
        if img.startswith("//"):
            img = "http:" + img
        desc = title + "\n" + re.search('<meta property="og:description" content="([^"]+)">', r, re.IGNORECASE | re.DOTALL).group(1)
        m = re.search('file: "([^"]+)"', r, re.IGNORECASE)
        if m:
            data2 = m.group(1)
            stream = util.item()
            stream["name"] = title
            stream["url"] = data2
            stream["img"] = img
            stream["desc"] = desc
            stream["resolver"] = "lmt"
            return [stream]
        elif re.search('src="http*://www.youtube.com/embed/([\w-]+).*"',r):
            m = re.search('src="http*://www.youtube.com/embed/([\w-]+).*"',r)
            video_id = m.group(1)
            #http://www.youtube.com/embed/RUyQ_JJ6A84?rel=0&fs=1&wmode=transparent
            data2 = YouTubeVideoUrl().extract(video_id)
            s = util.item()
            s["name"] = title
            s["url"] = data2
            s["desc"] = desc
            s["img"] = img
            s["resolver"] = "lmt"
            return [s]
        elif 'src="http://cdn.tiesraides.lv/lmtstraume.lv/' in r:
            m = re.search('src="(http://cdn\.tiesraides\.lv/[^"]+)"',r)
            url = m.group(1)
            # src="http://cdn.tiesraides.lv/lmtstraume.lv/live-record2-ip/40?c=614127284dcd58d8a84afcf498a3ac7a&v=1405"
            r = self._http_request(url)
            #http://edge-telia2.tiesraides.lv/live-record2/lmtstraume.lv.40_1/manifest.f4m
            m = re.search("'(http://.+?\.m3u8)'",r)
            data2 = m.group(1) if m else ""
            s = util.item()
            s["name"] = title
            s["url"] = data2
            s["desc"] = desc
            s["img"] = img
            s["resolver"] = "lmt"
            return [s]
        elif "//live.tiesraides.lv/lmtstraume.lv" in r:
            m = re.search('<div class="single-video-item video-picture">.+?src="([^"]+)"', r, re.DOTALL)
            url = "http:" + m.group(1)
            # src="http://cdn.tiesraides.lv/lmtstraume.lv/live-record2-ip/40?c=614127284dcd58d8a84afcf498a3ac7a&v=1405"
            r = self._http_request(url)
            #http://edge-telia2.tiesraides.lv/live-record2/lmtstraume.lv.40_1/manifest.f4m
            m = re.search("'(http://.+?\.m3u8)'",r)
            data2 = m.group(1) if m else ""
            s = util.item()
            s["name"] = title
            s["url"] = data2
            s["desc"] = desc
            s["img"] = img
            s["resolver"] = "lmt"
            return [s]
        elif "embed.php?salt=" in r:
            m = re.search('embed\.php\?salt=([^"]+)"', r)
            url = "http://g1.delphi.lv/vfe/data.php?video_id=%s" % m.group(1)
            r2 = self._http_request(url)
            js = json.loads(r2)
            s = util.item()
            s["name"] = js["data"]["title"]
            s["desc"] = re.sub("<.+?>", "", js["data"]["description"])
            s["img"] = js["data"]["poster"]
            s["resolver"] = "lmt"
            vers =  js["data"]["versions"].keys()
            ver = "HD" if "HD" in vers else "SD" if "SD" in vers else None
            if not ver:
                raise Exception("No stream found")
            sdata = js["data"]["versions"][ver]
            s["url"] = "http:" + sdata[1]["src"]
            return [s]

        else:
            raise Exception("No stream found")


                # streams = resolver.resolve(url)
            # for s in streams:
            #     s["name"] = title
            #     s["desc"] = desc
            #     s["img"] = img
            #     streams.append(s)
            # return streams


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()
