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

#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="",cfg_path=None):
        self.hidden = True # nerāda menu nestrādājošos avotus
        self.name = "cinemalive"
        self.title = "cinemalive.tv"
        self.img = "cinemalive.png" #"https://cinemalive.tv/assets/img/logo.png"
        self.desc = "Filmas latviski"
        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","back.png","Return back"))

        if clist=="home":
            content.extend([
                ("Search", "cinemalive::?s={0}","","Search"),
                #("Filmas latviski - visas", "cinemalive::filmaslatviski/","","Filmas latviski - visas"),
                ("Filmas angliski", "cinemalive::home_en","","Filmas angliski"),
                #("Filmas latviski - jaunākās", "cinemalive::filmaslatviski/?get=jaunakas","","Filmas latviski - jaunākās"),
                #("Filmas latviski - vertētākās", "cinemalive::filmaslatviski/?get=vertetakas","","Filmas latviski - vērtētākās"),
                #("Filmas latviski - skatitakās", "cinemalive::filmaslatviski/?get=skatitakas","","Filmas latviski - skatītākās"),
                #("Filmas latviski - animācija", "cinemalive::genre/animacija/","","Filmas latviski - animacijas"),
                #("Filmas latviski - ģimenes", "cinemalive::genre/gimenes/","","Filmas latviski - ģimenes"),
            ])
            r = self.call("filmaslatviski")
            i0 = r.find('<div class="menu">')
            result = re.findall(r'menu-item-41\d+"><a href="([^"]+)">([^<]+)</a>', r[i0:])
            for item in result:
                title = "Filmas latviski - "+item[1]
                data2 = item[0].replace("https://cinemalive.tv", "")  #+"lapa/1/"
                data2 = data2[1:]
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))
            return content

        elif clist=="home_en":
            content.extend([
                ("Search", "cinemalive::?s={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")
            i0 = r.find('<div class="menu">')
            result = re.findall(r'menu-item-4[23]\d+"><a href="([^"]+)">([^<]+)</a>', r[i0:])
            for item in result:
                title = "Movies English - "+item[1]
                data2 = item[0].replace("https://cinemalive.tv", "")  #+"lapa/1/"
                data2 = data2[1:]
                if not (data2.startswith("movie") or data2.startswith("genre")):continue
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))
            return content


        elif clist == "" in data:
            r = self.call(data)
            result = re.findall("<article>(.+?)</article>", r)
            for r2 in result:
                m = re.search('<div class="title"><a href="https://cinemalive.tv/([^"]+)">(.+?)</a></div>', r2)
                title = m.group(2)
                data2 = m.group(1)
                title = re.sub("<[^>]+>", "", title)
                m = re.search('<img src="([^"]+)"', r2)
                img = m.group(1).replace("-150x150", "-185x278") if m else ""
                m = re.search(r'<span class="year">(\d+)</span>', r2)
                year = m.group(1) if m else ""
                if year:
                    title = title + "(%s)" % year
                m = re.search(r"url\(https://cinemalive\.tv/static_main/assets/img/flags/(\w+)\.png\)", r2)
                flag = m.group(1) if m else ""
                if flag:
                    title = title + "[%s]" % flag
                m = re.search('<div class="contenido"><p>([^<]+)</p>', r2)
                desc = m.group(1) if m else ""

                content.append((title,self.name+"::"+data2,img,desc))
            return content

        elif clist in ("filmaslatviski","moviesenglish", "genre"):
            r0 = self.call(data)
            if not r0:
                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)
            result = re.findall('<article id="post.+?</article>', r0, re.IGNORECASE)
            for r in result:
                m = re.search('alt="([^"]+)"', r, re.IGNORECASE)
                title = m.group(1)
                m = re.search('class="quality">(.+?)</span>', r, re.IGNORECASE)
                sub = " [%s]" % m.group(1) if m else ""
                m = re.search(r"</h3><span>(\d+)</span>", r, re.IGNORECASE)
                gads = " (%s)" % m.group(1) if m else ""
                title = title + gads + sub
                m = re.search('<h3><a href="https://cinemalive.tv/([^"]+)"', r, re.IGNORECASE)
                data2 = m.group(1)
                m = re.search('img src="([^"]+)"', r, re.IGNORECASE)
                img = m.group(1) if m else ""
                m = re.search('class="texto">([^<]+)<', r, re.IGNORECASE)
                desc = m.group(1)
                #TODO - papildus info no apraksta
                content.append((title,self.name+"::"+data2,img,desc))
            m = re.search(r"""<span class="current">\d+</span><a href='https://cinemalive.tv/([^']+)'""", r0)
            if m:
                data2 = m.group(1)
                content.append(("Next page",self.name+"::"+data2,"next.png","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","")
        m = re.search(' class="wp-content"><p>(.+?)</p>', r, re.IGNORECASE)
        desc = m.group(1) if m else title
        m = re.search('<div class="poster"><img src="([^"]+)"', r, re.IGNORECASE)
        img = m.group(1) if m else ""

        #              <iframe class="metaframe rptss" src="https://cloudsany.com/i/tqxkulkkcind"
        m = re.search('<iframe class="metaframe rptss" src="([^"]+)"', r, re.IGNORECASE)
        if not m:
            raise Exception("Can not find stream")
        url = m.group(1)
        if "openload" in url:
            s = resolve(url)
            return s
        elif "cloudsany" in url:
            s = resolve(url)
            for s2 in s:
                s2["name"] = util.unescape(title)
                s2["desc"] = util.unescape(desc)
                s2["img"] = img
                s2["lang"] = lang
            return s

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


    #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