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

from SourceBase import SourceBase

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.hidden = True # nerāda menu nestrādājošos avotus
        self.name = "serialguru"
        self.title = "SerialGURU.ru"
        self.img = "http://serialguru.ru/images/xlogo_new.png.pagespeed.ic.0sre2_2OJN.png"
        self.desc = "Serialguru.ru portāla satura skatīšanās"
        self.country=country
        self.headers = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36
Referer: http://serialguru.ru/
""")
        self.headers2 = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://serialguru.ru/
""")
        self.url = "http://serialguru.ru/"
        #self.login()

    def login(self,user="",password=""):
        return True

    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","back.png","Return back"))

        if clist=="home":
            content.extend([
                ("Search", "serialguru::search/{0}","","Search content"),
                ("Last", "serialguru::last","","Last series"),
                ("Series", "serialguru::serials","","TV Series"),
                ("Shows", "serialguru::tv","","TV Shows"),
                ("Animations", "serialguru::mult","","Animation series"),

                #("Archive - all", "tvdom::arhivs_all","","Video archive all"),
            ])
            return content

        elif data == "last":
            r = self.call("")
            for item in re.findall(r'<li><a href="(http://serialguru\.ru/[^"]+)"><i>([^<]+)</i>  <i>([^<]+)</i> <b>([^<]+)</b></a></li>', r, re.DOTALL):
                title = item[1] + " - " + item[2]+"/"+item[3]
                img = ""
                data2 = item[0].replace(self.url, "")
                desc = title
                content.append((title, self.name+"::"+data2, img, desc))
            return content

        elif data=="serials":
            content.extend([
                ("All", "serialguru::serials?o=0&t=S","","All series"),
                ("Russian", "serialguru::serials?c%5B%5D=53&c%5B%5D=61&c%5B%5D=33&c%5B%5D=42&c%5B%5D=31&o=0&t=S","","Russian countries series"),
                ("English", "serialguru::serials?c%5B%5D=27&c%5B%5D=26&c%5B%5D=43&c%5B%5D=30&c%5B%5D=34&c%5B%5D=25&o=0&t=S","","English countries series"),
                ("Europe", "serialguru::serials?c%5B%5D=29&c%5B%5D=66&c%5B%5D=44&c%5B%5D=28&c%5B%5D=51&c%5B%5D=65&c%5B%5D=62&c%5B%5D=40&c%5B%5D=45&c%5B%5D=68&c%5B%5D=59&c%5B%5D=39&c%5B%5D=35&c%5B%5D=47&o=0&t=S","","European countries series"),
                ("Other", "serialguru::serials?c%5B%5D=36&c%5B%5D=32&c%5B%5D=67&c%5B%5D=63&c%5B%5D=60&c%5B%5D=64&c%5B%5D=38&c%5B%5D=52&c%5B%5D=41&c%5B%5D=58&c%5B%5D=57&c%5B%5D=37&c%5B%5D=50&c%5B%5D=46&o=0&t=S","","Other countries series"),
                #("Archive - all", "tvdom::arhivs_all","","Video archive all"),
            ])
            return content

        elif data=="tv":
            content.extend([
                ("All", "serialguru::tv?o=0&t=S","","All series"),
                ("Russian", "serialguru::tv?c%5B%5D=53&c%5B%5D=61&c%5B%5D=33&c%5B%5D=42&c%5B%5D=31&o=0&t=P","","Russian countries TV shows"),
                ("English", "serialguru::tv?c%5B%5D=27&c%5B%5D=26&c%5B%5D=43&c%5B%5D=30&c%5B%5D=34&c%5B%5D=25&o=0&t=P","","English countries TV shows"),
                ("Europe", "serialguru::tv?c%5B%5D=29&c%5B%5D=66&c%5B%5D=44&c%5B%5D=28&c%5B%5D=51&c%5B%5D=65&c%5B%5D=62&c%5B%5D=40&c%5B%5D=45&c%5B%5D=68&c%5B%5D=59&c%5B%5D=39&c%5B%5D=35&c%5B%5D=47&o=0&t=P","","European countries TV shows series"),
                ("Other", "serialguru::tv?c%5B%5D=36&c%5B%5D=32&c%5B%5D=67&c%5B%5D=63&c%5B%5D=60&c%5B%5D=64&c%5B%5D=38&c%5B%5D=52&c%5B%5D=41&c%5B%5D=58&c%5B%5D=57&c%5B%5D=37&c%5B%5D=50&c%5B%5D=46&o=0&t=P","","Other countries TV shows"),
                #("Archive - all", "tvdom::arhivs_all","","Video archive all"),
            ])
            return content

        elif data=="mult":
            content.extend([
                ("All", "serialguru::mult?o=0&t=S","","All series"),
                ("Russian", "serialguru::mult?c%5B%5D=53&c%5B%5D=61&c%5B%5D=33&c%5B%5D=42&c%5B%5D=31&o=0&t=M","","Russian countries animantions"),
                ("English", "serialguru::mult?c%5B%5D=27&c%5B%5D=26&c%5B%5D=43&c%5B%5D=30&c%5B%5D=34&c%5B%5D=25&o=0&t=M","","English countries animantions"),
                ("Europe", "serialguru::mult?c%5B%5D=29&c%5B%5D=66&c%5B%5D=44&c%5B%5D=28&c%5B%5D=51&c%5B%5D=65&c%5B%5D=62&c%5B%5D=40&c%5B%5D=45&c%5B%5D=68&c%5B%5D=59&c%5B%5D=39&c%5B%5D=35&c%5B%5D=47&o=0&t=M","","European countries animantions"),
                ("Other", "serialguru::mult?c%5B%5D=36&c%5B%5D=32&c%5B%5D=67&c%5B%5D=63&c%5B%5D=60&c%5B%5D=64&c%5B%5D=38&c%5B%5D=52&c%5B%5D=41&c%5B%5D=58&c%5B%5D=57&c%5B%5D=37&c%5B%5D=50&c%5B%5D=46&o=0&t=M","","Other countries animantions"),
                #("Archive - all", "tvdom::arhivs_all","","Video archive all"),
            ])
            return content

        elif clist=="search":
            if data.split("/")>1:
                term = data.split("/")[1]
            else:
                return content
            r = self.call("main/autocomplete?term=%s"%(term))
            if r=="null":
                return content
            js = json.loads(r)
            for item in js:
                title = item["name"].encode("utf8")
                data2 = item["url"].encode("utf8")
                img = "http://serialguru.ru/uploads/cover/"+item["image_s"].replace("_s","")+".jpg"
                rating = item["rating"].encode("utf8") if item["rating"] else ""
                desc = title +"\nRating:%s (%s+/%s-)"%(rating,item["plus_cnt"].encode("utf8"),item["minus_cnt"].encode("utf8"))
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        elif path=="serials" or path=="tv" or path=="mult":
            if path=="serials" and not "cat%5B%5D" in data:
                #content.append(("All", "serialguru::"+data+"&cat%5B%5D=","","All series"))
                categories = self.get_categories(path)
                for c in categories:
                    content.append((c[1], "serialguru::"+data+"&cat%5B%5D="+c[0],"",c[1]))
                return content
            else:
                r = self.call("main/load", params[1:], headers=self.headers2)
                for item in re.findall('<li><a href="([^"]+)"><div>.*?<img src="([^"]+)" alt="([^"]+)"[^<]*?><p>([^<]+)<i><span class="r">([^<]+)</span> <span class="plus">([^<]+)</span> <span class="minus">([^<]+)</span></i></p></div>([^<]+)</a></li>', r, re.DOTALL):
                    title = "%s (%s)"%(item[2],item[3])
                    img = item[1].replace("_s.jpg","_l.jpg")
                    data2 = item[0].replace(self.url,"")
                    desc = title +"\nRating:%s (%s+/%s-)"%(item[4],item[5],item[6])
                    content.append((title,self.name+"::"+data2,img,desc))
                page=int(re.search("o=(\d+)",data).group(1))
                data2 = re.sub("o=(\d+)","o=%s"%(page+15),data)
                content.append(("Next page",self.name+"::"+data2,"","Go to next page"))
                return content


        ### Pārraide
        else:
            r = self.call(clist)
            title0=re.search('<h2>(.+?)</h2>',r,re.DOTALL).group(1)
            m=re.search('<div class="description">(.+?)</div>',r,re.DOTALL)
            desc0=m.group(1) if m else ""
            desc0=desc0.replace("<p>","").replace("</p>","\n").replace('<a href="#">ПОКАЗАТЬ ПОЛНОСТЬЮ</a>',"")
            desc0=title0+"\n"+desc0.strip()
            img0=""
            m = re.search("http://serialguru.ru/main/playlist/\d+",r)
            if m:
                url = m.group()
            else:
                raise Exception ("No stream found")
            r = self._http_request(url)
            js = json.loads(r,"utf8")
            if not "/" in data: # sezonas
                for i,item in enumerate(js["playlist"]):
                    title = title0 + " - " + item["comment"].encode("utf8")
                    img = img0
                    data2 = "%s/%s"%(data,i)
                    desc = desc0
                    content.append((title,self.name+"::"+data2,img,desc))
            else:
                snum = int(data.split("/")[1])
                title1 = js["playlist"][snum]["comment"].encode('utf8')
                for i,item in enumerate(js["playlist"][snum]["playlist"]):
                    title = title0 + " - " + title1+"/"+item["comment"].encode("utf8")
                    img = img0
                    data2 = item["file"].encode("utf8")
                    desc = desc0
                    content.append((title,data2,img,desc))
            return content


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

    def get_categories(self,data):
        r = self.call(data)
        r2 = re.search('<td class="category">(.+?)</td>', r, re.DOTALL).group(1)
        items = re.findall(r'<a href="#" data-id="(\d+)">([^<]+)</a>', r2, re.DOTALL)
        return items


    def call(self, data,params = None, headers=None):
        if not headers: headers = self.headers
        #if not lang: lang = self.country
        url = self.url + data
        content = self._http_request(url,params, headers)
        return content

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