#!/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 resolver
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=""):
        self.name = "kinofilmnet"
        self.title = "KinoFilmNet.lv"
        self.img = "http://kinofilmnet.lv/MusuBaneri/1268.png"
        self.desc = "Kinofilmnet.lv satura skatīšanās"
        self.country=country
        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://kinofilmnet.lv/"


    ######### Entry point ########        
    def get_content(self, data):
        print "[kinofilmnet] get_content:", data
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        content=[]
        content.append(("..return", "back","","Return back"))
        
        if clist=="home":
            content.extend([
                ("Meklēt", "kinofilmnet::search/?q={0}","","Meklēt"),                
                ("Jaunākās", "kinofilmnet::jaunakas","","Visu žanru jaunākās filmas"),
                ("Top50", "kinofilmnet::top50","","Top 50 filmas"),
            ])
            r = self.call("")
            i = r.find('<div class="cat-title">Meklēt pēc žanriem</div>')
            if i<=0:
                return content
            for item in re.findall('<li><a href=".*load/([^"]+)">([^<]+)</a></li>', r[i:]):
                title = item[1]
                data2 = "filmas/" + item[0]
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))      
            return content
    
        elif clist=="search":
            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://kinofilmnet.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,self.img,"Next page"))               
            return content
            
        # Žanru saraksti ##
        elif clist in ("jaunakas","top50") or clist=="filmas" and len(plist)==3:
            if clist == "jaunakas":
                r = self.call("")
            else:
                r = self.call(data)
            #r = r.decode("cp1251").encode("utf8")
            result = re.findall(r'<div id="entryID\w+">.+?<img src="([^"]+)" alt="([^"]+)".+?data-link="([^"]+)".+?<span>([^<]*)</span>.+?<div class="movie-date">([^<]+)</div>.+?<div class="movie-director"><b>Žanrs:</b> ([^<]+)</div>.+?<div class="movie-text">([^<]+)</div>', r, re.DOTALL)
            for item in result:
                title = item[1]+"[%s]"%item[3]
                img = "http://kinofilmnet.lv"+item[0]
                data2 = item[2][1:]
                desc = "%s %s\n%s"%(item[4],item[5],item[6])
                content.append((title,self.name+"::"+data2,img,desc))                      
            m = re.search('href="/([^"]+)" onclick="[^"]+" ><span>&raquo;', r, re.DOTALL)
            if m:
                data2 = m.group(1)
                content.append(("Next page",self.name+"::"+data2,self.img,"Next page"))    
            return content      
         
        ### Seriāls ###
        elif clist=="filmas" and len(plist)==4:
            r = self.call(path)
            title0 = re.search("<h1>([^<]+)</h1>", r, re.DOTALL).group(1)
            desc0 = re.search('<div class="m-desc full-text clearfix">([^<]+)</div>', r, re.DOTALL).group(1)
            img0 = "http://kinofilmnet.lv" + re.search('<div class="m-img">.*?<img src="([^"]+)" alt', r, re.DOTALL).group(1)
            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+"?s=%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=="filmas" and len(plist) == 4 and "s"in qs:
            return True
        if not (clist=="filmas" and len(plist) == 4):
            return False
        if "sezona" in data:
            return False
        r = self.call(path)
        result = re.findall(r'iframe src="https://openload\.co/embed/[^/]+/"', r, re.DOTALL)
        if len(result)>1:
            return False
        else:
            return True

        
    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 "[kinofilmnet] 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)
        title = re.search("<h1>([^<]+)</h1>", r, re.DOTALL).group(1)
        desc = re.search('<div class="m-desc full-text clearfix">([^<]+)</div>', r, re.DOTALL).group(1)
        img = "http://kinofilmnet.lv" + re.search('<div class="m-img">.*?<img src="([^"]+)" alt', r, re.DOTALL).group(1)
        if "s" in qs: # serialā sērija
            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]
        streams =  resolver.resolve(url0)
        for s in streams:
            if "hqq." in url0 or "goo.gl" in url0:
                s["url"] = util.streamproxy_encode(s["url"],s["headers"])
                s["headers"]={}
            s["name"] = title
            s["desc"] = desc
            s["img"] = img
            s["type"] = self.stream_type(s["url"])
            #s["lang"] = lang        
        return streams
        
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