#!/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
import ssl
if "_create_unverified_context" in dir(ssl):
    ssl._create_default_https_context = ssl._create_unverified_context

API_URL = 'http://www.filmon.com/'
headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
#User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0
headers0 = headers2dict("""
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: deflate
Connection: keep-alive
""")
import HTMLParser
h = HTMLParser.HTMLParser()

class Source(SourceBase):

    def __init__(self,country="lv",cfg_path=None):
        #self.hidden = True
        self.name = "filmon"
        self.title = "FilmOn"
        self.img = "filmon.png"
        self.desc = "FilmOn portāla satura skatīšanās"
        self.headers = headers0

        self.country=country
        self.jstv = None
        self.session_key = None
        self.cookie = None

    def get_content(self, data):
        print "[filmon] 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

        if not self.jstv:
            self.jstv = self.get_tv_channels()
        #if not self.session_key: # TODO izskatās, ka strādā bez, vismaz ja nelogojas iekšā,  jānočeko
        #    html = self._http_request("http://www.filmon.com/api/init")
        #    js = json.loads(html)
        #    self.session_key = js["session_key"]

        content=[]
        content.append(("..return", "back","back.png","Return back"))

        if clist=="home":
            content.extend([
                ("Live streams", "filmon::tv","","TV live streams"),
                ("Video on demand", "filmon::vod","","Last videos"),
            ])
            return content

        ### TV Groups ###
        elif clist in ("tv","home"):
            for gr in self.jstv:
                title = gr["name"].encode("utf8")
                data2 = "group?id=%s"%gr["id"]
                img = gr["logo_148x148_uri"].encode("utf8")
                desc = gr["description"].encode("utf8")
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        ### TV group channels ###
        elif clist=="group":
            if "id" in qs:
                group_id = qs["id"]
            else:
                return content
            group = None
            for gr in self.jstv:
                if gr["id"]==group_id:
                    group = gr
                    break
            if not group:
                return content
            for ch in group["channels"]:
                title = ch["title"].encode("utf8")
                data2 = "channel?id=%s"%ch["id"]
                img = ch["big_logo"].encode("utf8")
                desc = ch["description"].encode("utf8") if ch["description"] else title
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        ### TV Channel ###
        elif clist == "channel" or clist == "video":
            if "id" in qs:
                ch_id = qs["id"]
            else:
                return ("No stream found %s"%data,"","","No stream found")
            ch = self.get_tv_channel_info(ch_id)
            if ch["now_playing"]:
                current_event = ch["now_playing"]["programme_name"] if "programme_name" in ch["now_playing"] else ""
            else:
                current_event = ""
            title = u"%s - %s"%(ch["title"],current_event)
            title = title.encode("utf8")
            if current_event:
                desc = ch["now_playing"]["programme_description"].encode("utf8")
            else:
                desc = title
            data2 = ""
            for t in ("SD","HD"):
                for s in ch["streams"]:
                    if s["name"]==t:
                        data2 = s["url"].encode("utf8")
                        break
                if data2: break
            return (title,data2,"",desc)

        ### VOD genres ###
        elif path in ("vod","vod/genres"):
            data = "vod/genres"
            js = self.call(data)
            for gr in js["response"]:
                title = gr["name"].encode("utf8")
                data2 = "vod/search?genre=%s&max_results=30&no_episode=true&start_index=0"%(gr["slug"].encode("utf8"))
                img = gr["images"][0]["url"].encode("utf8")
                desc = gr["description"].encode("utf8") if gr["description"] else title
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        ### VOD genre videos ###
        elif path == "vod/search":
            js = self.call(data)
            for vid in js["response"]:
                title = vid["title"].encode("utf8")
                if vid["type"]=="series":
                    title = "[Series] "+title
                data2 = "vod/movie?id=%s&type=%s"%(vid["id"],vid["type"].encode("utf8"))
                img = "http://static.filmon.com/assets/"+vid["poster"]["couchdb_url"].encode("utf8")
                desc = vid["description"].encode("utf8") if vid["description"] else title
                content.append((title,self.name+"::"+data2,img,desc))
            start_index = int(qs["start_index"]) if "start_index" in qs else 0
            if start_index+js["total"]<js["total_found"]:
                start_index += 30
                data2 = re.sub("start_index=\d+","start_index=%s"%start_index,data) if "start_index" in qs else data +"&start_index=30"
                content.append(("Next page",self.name+"::"+data2,"","Next page"))
            return content

        ### VOD video sigle/series ###
        elif path == "vod/movie":
            js = self.call(data)
            if js["response"]["type"] == "series":
                ids = ",".join(js["response"]["episodes"])
                data2 = "vod/movies?ids=%s"%ids
                js2 = self.call(data2)
                for vid in js2["response"]:
                    title = vid["title"].encode("utf8")
                    if vid["type"]=="series":
                        title = "[Series] "+title
                    data2 = "vod/movie?id=%s&type=%s"%(vid["id"],vid["type"].encode("utf8"))
                    img = "http://static.filmon.com/assets/"+vid["poster"]["couchdb_url"].encode("utf8")
                    desc = vid["description"].encode("utf8") if vid["description"] else title
                    content.append((title,self.name+"::"+data2,img,desc))
                return content
            else:
                title = js["response"]["title"].encode("utf8")
                desc = js["response"]["description"].encode("utf8") if js["response"]["description"] else title
                data2 = js["response"]["streams"]["low"]["url"].encode("utf8")
                return (title,data2,"",desc)

    def is_video(self,data):
        if "::" in data:
            data = data.split("::")[1]
        cmd = data.split("?")
        if cmd[0] in ("video","channel"):
            return True
        elif cmd[0] == "vod/movie" and "type=movie" in data:
            return True
        else:
            return False

    def call(self, data,headers=headers0,lang=""):
        if not lang: lang = self.country
        url = "http://www.filmon.com/api/" + data
        #if not "?" in url: url += "?session_key=%s"%self.session_key
        #if not "session_key=" in url: url += "&session_key=%s"%self.session_key
        #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 get_tv_channel_info(self,id):
        url = "http://www.filmon.com/ajax/getChannelInfo"
        headers = headers2dict("""
Host: www.filmon.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:41.0) Gecko/20100101 Firefox/41.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: deflate
DNT: 1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://www.filmon.com/tv/live
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
""")
        headers["Cookie"] = self.cookie
        data = "channel_id=%s&quality=low"%id
        response = urllib2.urlopen(urllib2.Request(url, headers=headers,data=data))
        html =  response.read()
        js = json.loads(html)
        return js

    #----------------------------------------------------------------------
    def get_tv_channels(self):
        """Get tv channels list"""
        headers = headers2dict("""
Host: www.filmon.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:41.0) Gecko/20100101 Firefox/41.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: deflate
DNT: 1
Connection: keep-alive
    """)

        url = "http://www.filmon.com/tv"
        response = urllib2.urlopen(urllib2.Request(url, headers=headers))
        if "set-cookie" in response.headers:
            self.cookie = response.headers["set-cookie"]
        html =  response.read()
        s = re.search("(?i)var groups = (.*);", html).groups(1)[0]
        js = json.loads(s)
        return js

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