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

#sys.path.insert(0,os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 
from resolver import resolve
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 = "cinemalive"
        self.title = "cinemalive.tv"
        self.img = "picons/cinemalive.png" #"https://cinemalive.tv/assets/img/logo.png"
        self.desc = "cinemalive.tv satura skatīšanās"
        self.country=country
        self.headers = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
""")
        self.headers2 = headers2dict("""
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept-Language: en-US,en;q=0.8
""")
        self.url = "https://cinemalive.tv/"
        #self.login()
        
            
    ######### Entry point ########
    def get_content(self, data):
        print "[cinemalive] 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([
                ("Search", "cinemalive::scripts/search.php?search={0}","","Search"),            
                ("Filmas latviski - visas", "cinemalive::filmaslatviski/visas/lapa/1","","Filmas latviski - visas"),
                ("Filmas angliski", "cinemalive::home_en","","Filmas angliski"),
                ("Filmas latviski - jaunākās", "cinemalive::filmaslatviski/jaunakas/lapa/1","","Filmas latviski - jaunākās"),
                ("Filmas latviski - vertētākās", "cinemalive::filmaslatviski/vertetakas/lapa/1","","Filmas latviski - vērtētākās"),
                ("Filmas latviski - skatitakās", "cinemalive::filmaslatviski/skatitakas/lapa/1","","Filmas latviski - skatītākās"),
            ])
            r = self.call("filmaslatviski")
            for item in re.findall(r'<li class="nav-submenu-item"><a href="/([\w/]+)">(.+?)</a></li>', r):
                title = "Filmas latviski - "+item[1]
                data2 = item[0]+"/lapa/1"
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))      
            return content

        elif clist=="home_en":
            content.extend([
                ("Search", "cinemalive::scripts/search.php?search={0}","","Search"),            
                ("Movies English - all", "cinemalive::moviesenglish/all/page/1","","Movies English - all"),
                ("Movies Latvian", "cinemalive::home","","Filmas latviski"),
                ("Movies English - newest", "cinemalive::moviesenglish/newestmovies/page/1","","Movies English - newest"),
                ("Movies English - top rated", "cinemalive::moviesenglish/toprated/page/1","","Movies English - top rated"),
                ("Movies English - most watched", "cinemalive::moviesenglish/mostwatched/page/1","","Movies English - most watched"),
            ])
            r = self.call("moviesenglish")
            for item in re.findall(r'<li class="nav-submenu-item"><a href="/([\w/]+)">(.+?)</a></li>', r):
                title = "Movies English - "+item[1]
                data2 = item[0]+"/page/1"
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))      
            return content

    
        elif "search.php" in data:
            
            r=self.call(path,params=params[1:],headers=self.headers2)
            result = re.findall(r'<div class="results.+?<a href="https://cinemalive\.tv/(.+?)">.+?<img src="(.+?)".+?<span style="color:#bcbcbc">([^<]+)</span> <span style="color:#5a606d;font-size:12px;">([^<]+)</span><br/>.+?<p class="dec" style="font-size:12px; color:#777;line-height:14px;">([^<]+)</p>', r, re.DOTALL)            
            for item in result:
                title = item[2]
                title0 = re.sub(" \(\d+\)","",title)
                if title0 == item[3]:
                    title = title+" [EN]"
                else:
                    title = title + "/"+ item[3]+" [LV]"
                title = util.unescape(title)
                data2 = item[0]
                img = item[1].replace("xs.","sm.")
                desc = util.unescape(item[4])
                content.append((title,self.name+"::"+data2,img,desc))            
            return content

        elif clist in ("filmaslatviski","moviesenglish"):
            r = self.call(data)
            if not r:
                return content
            result = re.findall(r'<div class="base-used">.+?<a href="https://cinemalive.tv/([^"]+)">.+?<img class="img-thumbnail" src="/([^"]+)" alt="([^"]+)"/>.+?<p class="year">(\d+)</p>', r, re.DOTALL)
            for item in result:
                title = item[2] + " (%s)"%item[3]
                data2 = item[0]
                img = "https://cinemalive.tv/"+item[1]
                title = util.unescape(title)
                desc = title
                content.append((title,self.name+"::"+data2,img,desc)) 
            m = re.search(r"""<a href='https://cinemalive\.tv/([^']+)' style="border-right:none;">»</a>""", r, re.DOTALL)
            if m:
                data2 = m.group(1)
                content.append(("Next page",self.name+"::"+data2,self.img,"Next page"))                                  
            return content      
         
        else:
            return content                            
              
    def is_video(self,data):
        source,data,path,plist,clist,params,qs = self.parse_data(data)        
        if clist=="movie":
            return True
        else:
            return False
                        
    def get_streams(self, data):
        print "[cinemalive] get_streams:", data
        source,data,path,plist,clist,params,qs = self.parse_data(data)
        r = self.call(path)
        if not r:
            return []
        streams = []
        title0 = re.search("<title>([^<]+)</title>", r).group(1)
        lang = "LV" if "Filma Online Latviski" in title0 else "EN"
        title = title0.replace(" - Filma Online Latviski","").replace(" - Movie Online English HD","")
        desc = re.search('<p class="plot">(.+?)</p>', r).group(1)
        img = "http://cinemalive.tv"+re.search('<img src="(.+?)" class="img-thumbnail"', r).group(1)
        
        m = re.search(r'<video id=.+?<source src="([^"]+\.mp4)"', r, re.DOTALL)
        if m:
            s = util.item()
            s["url"] = m.group(1)
            s["name"] = util.unescape(title)
            s["desc"] = util.unescape(desc)
            s["img"] = img
            s["type"] = self.stream_type(s["url"])
            s["lang"] = lang 
            return [s]
        
        #m = re.search('<div class="viboom-overroll"><iframe src="([^"]+)"', r)
        #if m:
        result = re.findall('<div id="video_container"><iframe src="(.+?)"', r)
        if result:
            streams = resolve(result[0])
            for s in streams:
                s["name"] = util.unescape(title)
                s["desc"] = util.unescape(desc)
                s["img"] = img
                s["type"] = self.stream_type(s["url"])
                s["lang"] = lang
            if len(result)>1:
                lang2 = "EN" if lang=="LV" else "LV"
                streams2 = resolve(result[1])
                for s in streams2:
                    s["name"] = util.unescape(title)
                    s["desc"] = util.unescape(desc)
                    s["img"] = img
                    s["type"]= self.stream_type(s["url"])
                    s["lang"] = lang2
                    streams.append(s)  
            return streams
        else:
            return []

                    
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