# -*- coding: utf-8 -*-
############################################################################################################################################################################                                                                                                                                       #                                                                                                                                                                          #
#                                                                                                                                                                          #
#    ##     .   **       #########.  ########   #########   ##     ##    #########   #########   #########   #########   #########   ########   #########   ##########     #
#    ##         ##       ##     ##     ###      ##     ##   ###    ##    ##          ##          ##     ##   ##     ##   ##     ##   ##         ##     ##   ##             #
#    ##         ##       ##     ##     ###      ##     ##   ## #   ##    ##          ##          ##     ##   ##     ##   ##     ##   ##         ##     ##   ##             #
#    ##         ##       ########      ###      ##     ##   ##  #  ##    #########   ##          ########    #########   ## ######   ########   ########    ##########     #
#    ##         ##       ##            ###      ##     ##   ##   # ##           ##   ##          ##    ##    ##     ##   ##          ##         ##    ##            ##     #
#    ##         ##       ##            ###      ##     ##   ##    ###           ##   ##          ##     ##   ##     ##   ##          ##         ##     ##           ##     #
#    #######    ##       ##     .      ###      #########   ##     ##    #########   ##########  ##      #   ##     ##   ##          ########   ##      #   ##########     #
############################################################################################################################################################################

import base64
import json
import re
import urlparse

from liptonscrapers.modules import cleantitle
from liptonscrapers.modules import client


def byteify(input):
    if isinstance(input, dict):
        return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()])
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input


class source:
    def __init__(self):
        self.priority = 1
        self.language = ['pl']
        self.domains = ['alltube.tv']

        self.base_link = 'http://alltube.tv'
        self.search_link = '/szukaj'
        self.moviesearch_link = '/index.php?url=search/autocomplete/&phrase=%s'
        self.tvsearch_cache = 'http://alltube.tv/seriale-online/'
        self.episode_link = '-Season-%01d-Episode-%01d'

    def get_rows(self, r, search_type):
        divs = client.parseDOM(r, 'div', attrs={'class': 'col-sm-12'})
        for div in divs:
            header = client.parseDOM(div, 'h2', attrs={'class': 'headline'})
            if header and header[0] == search_type:
                return client.parseDOM(div, 'div', attrs={'class': 'item-block clearfix'})

    def name_matches(self, names, names_found):

        for name in names:
            if name in names_found:
                return True
        return False

    def try_read_year(self, url):
        index = url.rfind('/')
        found_year = url[index - 4:index]
        if found_year.isdigit():
            return found_year
        return None

    def search(self, title, localtitle, year, search_type):
        try:
            r = client.request(urlparse.urljoin(self.base_link, self.search_link),
                               post={'search': cleantitle.query(title)})
            r = self.get_rows(r, search_type)

            names = [cleantitle.get(i) for i in [title, localtitle]]
            for row in r:
                url = client.parseDOM(row, 'a', ret='href')[0]
                names_found = client.parseDOM(row, 'h3')[0]
                if names_found.startswith('Zwiastun') and not localtitle.startswith('Zwiastun'):
                    continue
                names_found = names_found.split('/')
                names_found = [cleantitle.get(i) for i in names_found]
                if self.name_matches(names, names_found):
                    found_year = self.try_read_year(url)
                    if not found_year or found_year == year:
                        return url


        except:
            return

    def movie(self, imdb, title, localtitle, aliases, year):
        return self.search(title, localtitle, year, 'Filmy')

    def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
        return self.search(tvshowtitle, localtvshowtitle, year, 'Seriale')

    def episode(self, url, imdb, tvdb, title, premiered, season, episode):
        try:
            if url == None: return

            txts = 's%02de%02d' % (int(season), int(episode))
            result = client.request(url)
            result = client.parseDOM(result, 'li', attrs={'class': 'episode'})
            result = [i for i in result if txts in i][0]
            url = client.parseDOM(result, 'a', ret='href')[0]
            url = url.encode('utf-8')
            return url
        except:
            return

    def get_language_by_type(self, lang_type):
        if lang_type in ['Napisy', 'Lektor', 'Dubbing']:
            return 'pl', lang_type
        if lang_type == 'PL':
            return 'pl', None

        return 'en', None

    def sources(self, url, hostDict, hostprDict):
        try:
            sources = []

            if url == None: return sources

            url = urlparse.urljoin(self.base_link, url)

            result = client.request(url)

            links = client.parseDOM(result, 'tr')
            links = [(client.parseDOM(i, 'a', attrs={'class': 'watch'}, ret='data-iframe')[0],
                      client.parseDOM(i, 'img', ret='alt')[0],
                      client.parseDOM(i, 'td', attrs={'class': 'text-center'})[0]) for i in links]

            for i in links:
                try:
                    url1 = '%s?%s' % (url, i[0])
                    url1 = url1.encode('utf-8')
                    language, info = self.get_language_by_type(i[2]);

                    sources.append({'source': i[1].encode('utf-8'), 'quality': 'SD', 'language': language, 'url': url1,
                                    'info': info, 'direct': False, 'debridonly': False})
                except:
                    pass

            return sources
        except:
            return sources

    def resolve(self, url):
        try:
            myurl = url.split('?')
            mycookie = client.request(myurl[0], output='cookie', error=True)

            tmp = ' '
            tmp = base64.b64decode(tmp)
            _myFun = compile(tmp, '', 'exec')
            vGlobals = {"__builtins__": None, 'len': len, 'list': list, 'ord': ord, 'range': range}
            vLocals = {'abc': ''}
            exec (_myFun in vGlobals, vLocals)
            myFun1 = vLocals['abc']

            data = client.request(urlparse.urljoin(self.base_link, '/jsverify.php?op=tag'), cookie=mycookie)
            data = byteify(json.loads(data))
            d = {}
            for i in range(len(data['key'])):
                d[data['key'][i]] = data['hash'][i]
            tmp = ''
            for k in sorted(d.keys()):
                tmp += d[k]
            mycookie = 'tmvh=%s;%s' % (myFun1(tmp), mycookie)

            link = client.request(myurl[-1].decode('base64') + '&width=673&height=471.09999999999997', cookie=mycookie)
            match = re.search('<iframe src="(.+?)"', link)
            if match:
                linkVideo = match.group(1)
                return linkVideo
            return
        except:
            return
