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

headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
headers0 = headers2dict("""
Host: m-api.ustvnow.com
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
DNT: 1
Connection: keep-alive
""")
import HTMLParser
h = HTMLParser.HTMLParser()

class Source(SourceBase):

    def __init__(self,country="lv"):
        self.name = "ustvnow"
        self.title = "USTVNow"
        self.img = "http://watch.ustvnow.com/assets/ustvnow/img/ustvnow_og_image.png"
        self.desc = "USTVNow kanālu tiešraide"
        self.headers = headers0

        self.country=country
        self.token = ""
        cur_directory = os.path.dirname(os.path.abspath(__file__))
        self.config_file = os.path.join(cur_directory,self.name+".cfg")
        self.options = OrderedDict([("user","lietotajs"),("password","parole")])
        self.options_read()

    def login(self,user="",password=""):
        if not user: user=self.options["user"]
        if not password: password = self.options["password"]
        self.options_read()        
        headers = headers2dict("""
        Host: m-api.ustvnow.com
        Accept-Language: en-US,en;q=0.5
        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
        Connection: keep-alive
        """)

        url = "http://m-api.ustvnow.com/iphone/1/live/login?username=%s&password=%s&device=gtv&redir=0"%(user,password)
        #url = "http://m-api.ustvnow.com/gtv/1/live/login?username=%s&password=%s&device=gtv&redir=0"%(user,password)
        r = self._http_request(url,headers=headers)
        if 'success' in r:
            self.token = re.search('"token":"([^"]+)',r).group(1)
            return True
        else:
            return False

    def get_content(self, data):
        print "[tvdom] 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([
                ("TV live streams", "ustvnow::tvlive","","TV live streams"),
                ("Movies", "ustvnow::movies","","Movies (not implemented yet"),
                ("Recordings", "ustvnow::recordings","","Recordings (not implemented yet"),
            ])
            return content

        if clist=="movies":
            return content

        if clist=="recordings":
            return content

        ### Tiesraides kanalu saraksts ###
        elif data=="tvlive":
            if not self.token:
                if not self.login():
                    raise Exception("Can not login\nPlease check USTVNow username/password in\n/usr/lib/enigma2/python/Plugins/Extensions/sources/ustvnow.cfg file")
            data = "live/channelguide?token=%s"%self.token
            self.r = self.call(data)
            if not self.r:
                return content
            for item in self.r["results"]:
                if item["order"] == 1:    
                    title = item["stream_code"]
                    title =  h.unescape(title.decode("utf8")).encode("utf8")
                    img = "http://m-api.ustvnow.com/"+item["prg_img"] #item["img"]
                    data2 = "live/view?scode=%s&token=%s"%(item["scode"],self.token)
                    desc = "%s\n%s (+%s')\n%s"%(item["title"],item["event_time"],int(item["actualremainingtime"])/60,item["description"])
                    content.append((title,self.name+"::"+data2,img,desc))
            return content

        ### Tiesraides kanāls ###
        elif path == "live/view":
            url = "http://m-api.ustvnow.com/stream/1/%s"%data
            r = self._http_request(url)
            if not r:
                return ("No stream found %s"%data,"","","No stream found")
            r = json.loads(r)
            if self.r:
                ch = qs["scode"]
                for item in self.r["results"]:
                    if item["order"] == 1 and item["scode"] == ch:
                        title = item["stream_code"]
                        title = "%s - %s (%s)"%(item["stream_code"],item["title"],item["event_time"])
                        img = "http://m-api.ustvnow.com/"+item["prg_img"]
                        data2 = "live/view?scode=%s&token=%s"%(item["scode"],self.token)
                        desc = "%s\n%s (+%s')\n%s"%(item["title"],item["event_time"],int(item["actualremainingtime"])/60,item["description"])
            else:
                title = data
            data2 = r["stream"]
            desc = title
            img = ""          
            return (title,data2,img,desc)               

    def is_video(self,data):
        if "::" in data:
            data = data.split("::")[1]
        if "live/view" in data:
            return True
        else:
            return False

    def call(self, data,headers=headers0,lang=""):
        if not lang: lang = self.country
        url = "http://m-api.ustvnow.com/gtv/1/"+data
        content = self._http_request(url)
        result = None
        if content:
            try:
                result = json.loads(content)
            except Exception, ex:
                return None
        return result


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