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

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 = "enigma2"
        self.title = "Engima2"
        self.img = "enigma2.png"
        self.desc = "Get streams from engima2 sat receiver"
        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.url = "http://login.tvplayhome.lt:8081/sb/public/"
        cur_directory = os.path.dirname(os.path.abspath(__file__))
        if not cfg_path: cfg_path = cur_directory
        self.config_file = os.path.join(cfg_path,self.name+".cfg")
        self.options = OrderedDict([("host", "localhost"), ("user",""),("password","")])
        self.options_read()

        if self.options["user"]:
            self.url = "http://%s:%s@%s/api/" % (self.options["user"], self.options["password"],self.options["host"])
        else:
            self.url = "http://%s/api/" % (self.options["host"])

    ######### Entry point ########
    def get_content(self, data):
        print "[enigma2] 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":
            data3 = "getcurrent"
            r2 = self.call(data3)
            event = r2["now"]
            title, img, desc = self.get_title_desc(event)
            content.append(("Current stream: "+title, self.name+"::"+"streamcurrent", img, desc))
            r = self.call("bouquets?stype=tv")
            for item in r["bouquets"]:
                title = item[1]
                data2 = "getservices?sRef=%s" % item[0]
                #data2 = "epgbouquet?bRef=%s" % item[1]
                content.append((title, self.name+"::"+data2, self.img, title))
            return content

        elif clist == "getservices":
            r = self.call(data)
            data3 = data.replace("getservices?sRef", "epgbouquet?bRef")
            r2 = self.call(data3)
            for item in r["services"]:
                title = item["servicename"]
                data2 = "stream?ref=%s&name=%s" % (item["servicereference"], title)
                img = self.img
                desc = title
                for item2 in r2["events"]:
                    if item2["sref"] == item["servicereference"]:
                        title, img, desc = self.get_title_desc(item2)
                        break
                content.append((title,self.name+"::"+data2, img,desc))
            return content

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

    def get_title_desc(self, event):
        t1 = event["begin_timestamp"]
        t2 = event["begin_timestamp"] + event["duration_sec"]
        t1 = datetime.datetime.fromtimestamp(t1).strftime("%H:%M")
        t2 = datetime.datetime.fromtimestamp(t2).strftime("%H:%M")
        title = "%s - %s [%s-%s]" % (event["sname"], event["title"], t1, t2)
        desc = event["shortdesc"]
        if event["longdesc"]:
            desc += "\n" + event["longdesc"]
        img = event["sref"][:-1].replace(":", "_") + ".png"
        img = self.url.replace("/api/", "/picon/") + img
        return title, img, desc


    def is_video(self,data):
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        if clist in ("stream", "streamcurrent"):
            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 "[enigma2] get_streams:", data
        if not self.is_video(data):
            return []
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        if "streamcurrent" in data:
            data3 = "getcurrent"
            r2 = self.call(data3)
            event = r2["now"]
            data = data.replace("streamcurrent", "streamcurrent.m3u")
        else:
            data3 = data.replace("stream?ref=","epgservicenow?sRef=")
            r2 = self.call(data3)
            event = r2["events"][0]
            data = data.replace("stream", "stream.m3u")
        title, img, desc = self.get_title_desc(event)

        r = self._http_request(self.url+data)
        m =  re.search("(http(s)*:.+)", r)
        if not m:
            raise Exception("No streams found!")
        data2 = m.group(1)
        #data2 = "http://videolink"
        stream = util.item()
        stream["name"] = title
        stream["url"] = data2
        stream["img"] = img
        stream["desc"] = desc
        stream["resolver"] = "enigma2"
        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()
