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

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="",cfg_path=None):
        self.hidden = True # nerāda menu nestrādājošos avotus
        self.name = "movieplace"
        self.title = "MoviePlace.lv"
        self.img = "movieplace.png"
        self.desc = "Movieplace.lv - filmas 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://movieplace.lv/"


    ######### Entry point ########
    def get_content(self, data):
        print "[movieplace] 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", "movieplace::search/?q={0}","","Meklēt"),
                ("Jaunākās filmas", "movieplace::load/?page1","","Visu žanru jaunākās filmas"),
                ("Jaunākie seriāli", "movieplace::dir/?page1","","Visu žanru jaunākās filmas"),
                #("Top50 filmas", "movieplace::index/top_50_filmas/0-4","","Top 50 filmas"),
            ])
            r = self.call("load/")
            #i = r.find('<div class="cat-title">Meklēt pēc žanriem</div>')
            #if i<=0:
            #    return content
            i = 0
            for item in re.findall('<a href="/([^"]+)" class="catName">([^>]+)</a>', r[i:]):
                title = item[1]
                data2 = item[0]+"-1"
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        elif clist=="search":
            # TODO
            r=self.call(data)
            result = re.findall('<a href="([^"]+)"> (.+?) </a></div>.+?> (.+?)</div>', r, re.DOTALL)
            for item in result:
                title = item[1].replace("<b>","").replace("</b>","")
                data2 = item[0].replace("http://movieplace.lv/","")
                img = self.img
                desc = item[2].replace("<b>","").replace("</b>","")
                content.append((title,self.name+"::"+data2,img,desc))
            if '<span>&raquo;</span>' in r:
                m = re.search("p=(\d+)",data)
                if m:
                    page = int(m.group(1))+1
                    data2 = re.sub(r"p=\d+", r"p=%s"%page, data)
                    content.append(("Next page",self.name+"::"+data2,"next.png","Next page"))
            return content

        # Filmu saraksti ##
        elif clist in ["load","dir"] and len(plist)<=3:
            if clist == "jaunakas":
                r = self.call("")
            else:
                r = self.call(data)
            #r = r.decode("cp1251").encode("utf8")
            if clist == "load":
                result = re.findall(r' <a href="/([^"]+)" alt="([^"]+)"><img src="/([^"]+)" title="([^"]+)">.+?<div class="years">([^<]+)</div>\s+<div class="country">([^<]+)</div>', r, re.DOTALL)
            else:
                result = re.findall(r' <a href="/([^"]+)" alt="([^"]+)"><img src="/([^"]+)" title="[^"]+">.+?<span>([^<]+)</span>\s*<div class="country">([^<]+)</div>', r, re.IGNORECASE | re.DOTALL)
            for item in result:
                title = item[1]+" [%s]"%item[4] if clist=="load" else item[1]+" / %s [%s]"%(item[3],item[4])
                img = "http://movieplace.lv/"+item[2]
                data2 = item[0]
                desc = "%s\n%s"%(title,item[5]) if clist=="load" else title
                content.append((title,self.name+"::"+data2,img,desc))
            m = re.search('<[ab] class="swchItemA*1"( href="/([^"]+)" onclick="[^"]+")*><span>([^<]+)</span></[ab]> </span>', r, re.DOTALL)
            if m:
                if m.group(1):
                    page = int(re.search("\d+$",data).group())
                    page = page+1
                    data2 = re.sub("\d$","%s"%page,data)
                    content.append(("Next page",self.name+"::"+data2,"next.png","Next page"))
            return content

        ### Seriāls ###
        elif clist=="dir" and len(plist)==4:
            r = self.call(path)
            title0 = re.search('<h2 class="title" itemprop="name">(.+?)</h2>', r, re.DOTALL).group(1)
            m = re.search(r'<span>VALODA:</span> <b><em itemprop="alternativeHeadline"><a href="[^"]*" class="entAllCats">([^<]+)</a></em></b></div>\s+?<div><span>SEZONA:</span> <b>([^<]+)</b></div>', r, re.IGNORECASE | re.DOTALL)
            if m:
                title0 = "%s / Season %s [%s]"%(title0,m.group(2),m.group(1))
            desc0 = title0
            img0 = "http://movieplace.lv" + re.search('<img src="(.+?)".+?itemprop="image">', r, re.DOTALL).group(1)
            #TODO
            result = re.findall(r'<summary>([^<]+)</summary><iframe src="https://openload\.co/embed/[^/]+/"', r, re.DOTALL)
            i = 1
            for item in result:
                title = title0+" - " + item
                data2 = data+"?e=%s"%i
                img = img0
                desc = desc0
                content.append((title,self.name+"::"+data2,img,desc))
                i += 1
            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 clist=="dir" and len(plist) == 4 and "e"in qs: # sērija
            return True
        elif clist=="load" and len(plist) == 4:
            return True
        else:
            return False

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

    def get_streams(self,data):
        print "[movieplace] 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)
        if clist=="load":
            m = re.search('<h2 class="title" itemprop="name">([^<]+)</h2>', r, re.DOTALL)
            title = re.search('<itemprop="name">(.+?)</itemprop="name">', r, re.DOTALL).group(1)
            m = re.search(r'<div role="tabpanel" class="tab-pane fade in active" id="heading-tab4">\s*(.+?)\s*</div>', r, re.DOTALL)
            desc = m.group(1) if m else title
            m = re.search('<meta property="og:image" content="([^"]+)" />', r, re.DOTALL)
            img = m.group(1) if m else ""
            rr = []
            for m in re.finditer("(RU|ENG|LAT|LAT SUB)<BR( /)*>.*?>?<BR( /)*>.*?<iframe", r, re.IGNORECASE | re.DOTALL):
                if len(rr)>0:
                    rr[-1]["end"] = m.start()
                rr.append({"lang":m.group(1),"start":m.start(),"end":len(r)})
            streams = []
            for m in re.finditer(r'src="(https*://(goo\.gl|songs2dl|kodik|cdn\.kapnob|hqq|openload|sv1.servkino|vidwatch|online\.kinozz).+?)"', r, re.IGNORECASE | re.DOTALL):
                url = m.group(1)
                lang = "?"
                for rrr in rr:
                    if m.start()>rrr["start"] and m.start()<rrr["end"]:
                        lang = rrr["lang"]
                        break
                for s in resolver.resolve(url):
                    s["name"] = title
                    s["desc"] = desc
                    s["img"] = img
                    s["type"] = self.stream_type(s["url"])
                    s["lang"] = lang
                    streams.append(s)
            return streams


        elif clist=="dir" and "e" in qs: # serialā sērija
            #TODO
            result = re.findall(r'<summary>([^<]+)</summary><iframe src="([^"]+)"', r, re.DOTALL)
            i = int(qs["s"])-1
            url0 = result[i][1]
            title = title + " - " + result[i][0]
        else:
            #iframe src="https://openload.co/embed/wlw6Vl9zwL0/"
            result = re.findall(r'<iframe src="([^"]+)"', r, re.DOTALL)
            if not result:
                return []
            url0 = result[0]
        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"
    run.run(source, data)
    sys.exit()
