#!/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
import base64
from collections import OrderedDict
import sys


headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
import util
    
class Source(SourceBase):
    
    def __init__(self,country=""):
        self.name = "filmix"
        self.title = "filmix.me"
        self.img = "http://cs5324.vk.me/g33668783/a_903fcc63.jpg"
        self.desc = "filmix.me satura skatīšanās"
        self.country=country
        self.headers = headers2dict("""
Host: filmix.me
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 = "https://filmix.me/"
        #self.login()
        
    def login(self,user="",password=""):
        return True
            
    def get_content(self, data):
        print "[filmix] 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","","Return back"))
        
        if clist=="home":
            content.extend([
                ("Search", "filmix::search/{0}","","Search"),                
                ("Movies", "filmix::movies","","Movies"),
                ("Series", "filmix::series","","TV Series"),
                ("Cartoons", "filmix::cartoons","","Cartoons"),
            ])
            return content
    
        #elif clist=="search":
            # TODO
            #return content

        elif data in ("movies","series","cartoons"):
            r = self.call("")
            r = r.decode("cp1251").encode("utf8")
            if data == "movies":
                sname = "Фильмы"
            elif data=="series":
                sname = "Сериалы"
            else:
                sname = "Мультфильмы"
            # <span class="menu-title">Фильмы</span>
            m = re.search('<span class="menu-title">%s</span>(.+?)<li>\s+?<span'%sname, r, re.DOTALL|re.UNICODE)
            if not m: return content
            r2 = m.group(1)
            result = re.findall(r'<a .*?href="https://filmix\.me/([^"]+)".*?>([^<]+)</', r2, re.DOTALL)
            for item in result:
                if "catalog" in item[0]: continue
                title = item[1]
                data2 = item[0]
                img = self.img
                desc = title
                content.append((title,self.name+"::"+data2,img,desc))      
            return content      
         
        ## Video/seriāla spēlēšana
        elif clist=="play":
            r = self.call(path)
            r = r.decode("cp1251").encode("utf8")
            title = title0 = util.unescape(re.search("titlePlayer = '([^']+)'", r, re.DOTALL).group(1))
            m = re.search('<meta itemprop="thumbnailUrl" content="([^"]+)',r,re.DOTALL)
            img = m.group(1) if m else self.img
            m = re.search('<meta itemprop="duration" content="([^"]+)" />', r, re.DOTALL)
            duration = "(%s)"%m.group(1) if m else ""
            m = re.search('<p itemprop="description"[^>]+>([^<]+)<', r, re.DOTALL)
            desc = desc0 =  util.unescape(m.group(1).strip()) if m else ""
            
            #url2 = re.search('<div id="play-descr" class="title-page">.+?<a href="([^"]+)"', r, re.DOTALL).group(1)
            #r2 = self._http_request(url2)
             
            m = re.search("videoLink = '([^']+)'", r, re.DOTALL)
            if not m:
                raise Exception("Can not find video link")
            video_link = m.group(1)
            if video_link<>'{video-link}':
                video_link = self.decode_uppod_text(video_link)
                streams = self.get_streams2(video_link)
                data2 = streams[0][1]
                content = (title,data2,img,desc)
                return content
            else:
                m = re.search("plLink = '([^']+)'", r, re.DOTALL)
                if not m:
                    raise Exception("Can not find video link")
                pl_link = m.group(1)
                pl_link = self.decode_uppod_text(pl_link)
                js = self._http_request(pl_link)
                js = self.decode_uppod_text(js)
                js = json.loads(js)
                if "s" in qs and "e" in qs:
                    s = int(qs["s"])
                    e = int(qs["e"])
                    serie = js["playlist"][s-1]["playlist"][e-1]["comment"].encode("utf8")
                    title = title0+" - "+ serie
                    data2 = js["playlist"][s-1]["playlist"][e-1]["file"].encode("utf8")
                    streams = self.get_streams2(data2)
                    data2=streams[0][1]
                    desc = serie +"\n"+desc0
                    content = (title,data2,img,desc)
                    return content
                
                elif "s" in qs:
                    s = int(qs["s"])
                    for i,ep in enumerate(js["playlist"][s-1]["playlist"]):
                        title = title0+" - "+js["playlist"][s-1]["playlist"][i]["comment"].encode("utf8")
                        serie = js["playlist"][s-1]["playlist"][i]["comment"].encode("utf8")
                        data2 = data+"&e=%s"%(i+1)
                        desc = serie +"\n"+desc0
                        content.append((title,self.name+"::"+data2,img,desc)) 
                else:
                    for i,ep in enumerate(js["playlist"]):
                        title = title0 +" - "+js["playlist"][i]["comment"].encode("utf8")
                        serie = js["playlist"][i]["comment"].encode("utf8")
                        data2 = data+"?s=%s"%(i+1)
                        desc = serie +"\n"+desc0
                        content.append((title,self.name+"::"+data2,img,desc)) 
                return content                    
                #r = self._http_request(url)
            
        
        ### saraksts ### 
        else:
            r = self.call(data)
            r = r.decode("cp1251").encode("utf8")
            for r2 in re.findall('<article class="shortstory line".+?</article>', r, re.DOTALL):
                m = re.search(r'<a href="https://filmix\.me/play/(\d+)" class="watch icon-play">', r2, re.DOTALL)
                if not m: continue
                vid = m.group(1)
                data2 = "play/%s"%vid
                #title = re.search('itemprop="name">([^<]+)</div>', r2, re.DOTALL).group(1)
                title = re.search('itemprop="name" content="([^"]+)"', r2, re.DOTALL).group(1)
                m = re.search('itemprop="alternativeHeadline" content="([^"]+)"', r2, re.DOTALL)
                if m:
                    title = title + "/"+m.group(1)
                m = re.search('<img src="([^"]+.jpg)"', r2, re.DOTALL)
                img = "http://filmix.me"+m.group(1) if m else self.img
                m = re.search(r'<a itemprop="copyrightYear".+?>(\d+)<', r2, re.DOTALL)
                if m:
                    year = m.group(1) if m else ""
                    title = "%s (%s)"%(title,year)
                title = util.unescape(title)
                genre = re.findall('<a itemprop="genre"[^>]+?">([^<]+)</a>', r2, re.DOTALL)
                genre = ",".join(genre)
                m = re.search('<p itemprop="description">([^<]+)</p>', r2, re.DOTALL)
                desc0 = util.unescape(m.group(1)) if m else ""
                m = re.search('<div class="quality">([^<]+)</div>', r2, re.DOTALL)
                quality = m.group(1) if m else ""
                actors = re.findall('itemprop="actor">([^<]+)<', r2, re.DOTALL)
                actors = ",".join(actors)
                desc="%s\n%s\n%s\n%s\n%s"%(title,genre,desc0,actors,quality)
                content.append((title,self.name+"::"+data2,img,desc))
            if '<div class="navigation">' in r:
                m = re.search(r'href="https://filmix\.me/([^"]+)" class="next icon-arowRight btn-tooltip"', r, re.DOTALL)
                if m:
                    data2 = m.group(1)
                else:
                    m = re.search("/page/(\d)+",data)
                    if m:
                        page = int(m.group(1))+1
                        data2 = re.sub("/page/(\d)+", "/page/%s"%page, data)
                    else:
                        data2 = data + "/page/2"
                content.append(("Next page",self.name+"::"+data2,self.img,"Next page"))
                        
            return content                            
              
    def is_video(self,data):
        if "::" in data:
            data = data.split("::")[1] 
        path = data.split("?")[0]
        clist = path.split("/")[0]
        params = data[data.find("?"):] if "?" in data else ""
        
        if clist == "play" and "s=" in data and "e=" in data:
            return True
        elif clist=="play" and not params:
            r = self.call(path)
            #r = r.decode("cp1251").encode("utf8")
            title = title0 = util.unescape(re.search("titlePlayer = '([^']+)'", r, re.DOTALL).group(1))
            m = re.search("videoLink = '([^']+)'", r, re.DOTALL)
            if not m:
                raise Exception("Can not find video link")
            video_link = m.group(1)
            if video_link=='{video-link}':
                return False
            else:
                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 decode_uppod_text(self, text): 
        Client_codec_a = ["l", "u", "T", "D", "Q", "H", "0", "3", "G", "1", "f", "M", "p", "U", "a", "I", "6", "k", "d", "s", "b", "W", "5", "e", "y", "="]
        Client_codec_b = ["w", "g", "i", "Z", "c", "R", "z", "v", "x", "n", "N", "2", "8", "J", "X", "t", "9", "V", "7", "4", "B", "m", "Y", "o", "L", "h"]    
        text = text.replace("\n", "").strip()
        for i in range(len(Client_codec_a)):
            char1 = Client_codec_b[i]
            char2 = Client_codec_a[i]
            text = text.replace(char1, "___")
            text = text.replace(char2, char1)
            text = text.replace("___", char2)
        result = base64.b64decode(text)
        print result
        return result
    
    def get_streams2(self,url0):
        m = re.search("\[([\d,]+)]",url0)
        if not m:
            return [("?",url0)]
        res = m.group(1)
        streams=[]
        for res in res.split(","):
            if not res: continue
            url=re.sub("\[[\d,]+]",res,url0)
            streams.append((res,url))
        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