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

import re

from platformcode import config, logger, platformtools
from core.item import Item
from core import httptools, scrapertools, servertools, tmdb


host = 'https://yandispoiler.net/'


def do_downloadpage(url, post=None, headers=None):
    data = httptools.downloadpage(url, post=post, headers=headers).data

    if not data:
        if not '/?s=' in url:
            if config.get_setting('channels_re_charges', default=True): platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Re-Intentanto acceso[/COLOR]')

            timeout = config.get_setting('channels_repeat', default=30)

            data = httptools.downloadpage(url, post=post, headers=headers, timeout=timeout).data

    if '<title>Just a moment...</title>' in data:
        if not '/?s=' in url:
            platformtools.dialog_notification(config.__addon_name, '[COLOR red][B]CloudFlare[COLOR orangered] Protection[/B][/COLOR]')
        return ''

    return data



def mainlist(item):
    logger.info()
    itemlist = []

    itemlist.append(item.clone( title = 'Buscar ...', action = 'search', search_type = 'all', text_color = 'yellow' ))

    itemlist.append(item.clone( title = 'Películas', action = 'mainlist_pelis', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( title = 'Doramas', action = 'mainlist_series', text_color = 'firebrick' ))

    return itemlist


def mainlist_pelis(item):
    logger.info()
    itemlist = []

    itemlist.append(item.clone( title = 'Buscar película ...', action = 'search', search_type = 'movie', text_color = 'deepskyblue' ))

    itemlist.append(item.clone( title = 'Catálogo', action = 'list_all', url = host + 'peliculas/', search_type = 'movie' ))

    itemlist.append(item.clone( title = 'Por idioma', action = 'idiomas', search_type = 'movie' ))

    itemlist.append(item.clone( title = 'Por año', action = 'anios', search_type = 'movie' ))

    return itemlist


def mainlist_series(item):
    logger.info()
    itemlist = []

    itemlist.append(item.clone( title = 'Buscar dorama ...', action = 'search', search_type = 'tvshow', text_color = 'firebrick' ))

    itemlist.append(item.clone( title = 'Catálogo', action = 'list_all', url = host + 'series/', search_type = 'tvshow' ))

    itemlist.append(item.clone( title = 'Últimos episodios', action = 'news_epis', url = host, search_type = 'tvshow', text_color = 'cyan' ))

    itemlist.append(item.clone( title = 'Episodios', action = 'last_epis', url = host + 'episodios/', group = 'Epis', search_type = 'tvshow' ))

    itemlist.append(item.clone( title = 'Por idioma', action = 'idiomas', search_type = 'tvshow' ))

    itemlist.append(item.clone( title = 'Por año', action = 'anios', search_type = 'tvshow' ))

    return itemlist


def idiomas(item):
    logger.info()
    itemlist = []

    if item.search_type == 'movie': text_color = 'deepskyblue'
    else: text_color = 'firebrick'

    itemlist.append(item.clone( title = 'En castellano', action = 'list_all', url = host + 'audios/castellano/', text_color = text_color ))

    itemlist.append(item.clone( title = 'En latino', action = 'list_all', url = host + 'audios/latino/', text_color = text_color ))

    itemlist.append(item.clone( title = 'Subtitulado', action = 'list_all', url = host + 'audios/sub-espanol/', text_color = text_color ))

    return itemlist


def anios(item):
    logger.info()
    itemlist = []

    if item.search_type == 'movie': text_color = 'deepskyblue'
    else: text_color = 'firebrick'

    from datetime import datetime

    current_year = int(datetime.today().year)

    for x in range(current_year, 1999, -1):
        url = host + 'estreno/' + str(x) + '/'

        itemlist.append(item.clone( title = str(x), url = url, action = 'list_all', text_color = text_color ))

    return itemlist


def list_all(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    if '>Añadido recientemente<' in data:
        bloque = scrapertools.find_single_match(data, '>Añadido recientemente<(.*?)<span class="copyright-btm">')
    else: bloque = data

    matches = re.compile('<div id="item-(.*?)</div> </div> </div></div>').findall(bloque)

    for match in matches:
        url = scrapertools.find_single_match(match, '<a href="(.*?)"')

        title = scrapertools.find_single_match(match, 'title="(.*?)"')

        if not url or not title: continue

        thumb = scrapertools.find_single_match(match, 'src="(.*?)"')

        title = title.replace('&#039;', '').replace('&#8217;', "'")

        tipo = 'movie' if '/peliculas/' in url else 'tvshow'

        if tipo == 'movie':
            if item.search_type == 'tvshow': continue

            itemlist.append(item.clone( action='findvideos', url=url, title=title, thumbnail=thumb,
                                        contentType='movie', contentTitle=title, infoLabels={'year': '-'} ))

        if tipo == 'tvshow':
            if item.search_type == 'movie': continue

            data_url = scrapertools.find_single_match(match, 'data-url="(.*?)"')

            SerieName = data_url.replace('-', ' ').capitalize()

            itemlist.append(item.clone( action='temporadas', url=url, data_url = data_url, title=title, thumbnail=thumb,
                                        contentSerieName = SerieName, contentType = 'tvshow', infoLabels={'year': '-'} ))

    tmdb.set_infoLabels(itemlist)

    if itemlist:
        if '<div class="pagination">' in data:
            bloque = scrapertools.find_single_match(data, '<div class="pagination">(.*?)</main>')

            next_page = scrapertools.find_single_match(bloque, '<span class="current">.*?' + "href='(.*?)'")

            if next_page:
                if '/page/' in next_page:
                    itemlist.append(item.clone( title = 'Siguientes ...', url = next_page, action = 'list_all', text_color = 'coral' ))

    return itemlist


def news_epis(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    bloque = scrapertools.find_single_match(data, '>Últimos episodios<(.*?)>Ver más episodios<')

    matches = re.compile('<div class="sideranking-item"(.*?)</div> </div> </div>').findall(bloque)

    for match in matches:
        url = scrapertools.find_single_match(match, '<a href="(.*?)"')

        title = scrapertools.find_single_match(match, 'title="(.*?)"')

        if not url or not title: continue

        thumb = scrapertools.find_single_match(match, 'src="(.*?)"')

        title = title.replace('&#039;', '').replace('&#8217;', "'").replace('&#215;', ' ').strip()

        SerieName = scrapertools.find_single_match(match, 'alt="(.*?)"')

        if ':' in SerieName: SerieName = SerieName.split(":")[0]

        SerieName = SerieName.strip()

        season = scrapertools.find_single_match(match, '<span class="sideranking-episode-label">T(.*?)x').strip()

        if not season: season = 1

        epis = scrapertools.find_single_match(match, '<span class="sideranking-episode-label">.*xE(.*?)</span>').strip()

        if not epis: epis = 1

        if ':' in title: title = title.split(":")[0]

        titulo = str(season) + 'x' + str(epis) + ' ' + title

        itemlist.append(item.clone( action='findvideos', title = titulo, thumbnail = thumb, url = url,
                                    contentSerieName = SerieName, contentType = 'episode', contentSeason = season, contentEpisodeNumber = epis ))

    tmdb.set_infoLabels(itemlist)

    return itemlist


def last_epis(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    matches = re.compile('<div id="item-(.*?)</div> </div> </div></div>').findall(data)

    for match in matches:
        url = scrapertools.find_single_match(match, '<a href="(.*?)"')

        data_url = scrapertools.find_single_match(match, 'data-url="(.*?)"')

        title = scrapertools.find_single_match(match, 'title="(.*?)"')

        if not url or not data_url or not title: continue

        thumb = scrapertools.find_single_match(match, 'src="(.*?)"')

        title = title.replace('&#039;', '').replace('&#8217;', "'").replace('&#215;', ' ').strip()

        SerieName = data_url.replace('-', ' ').capitalize()

        if " 1x" in SerieName: SerieName = SerieName.split(" 1x")[0]
        elif " 2x" in SerieName: SerieName = SerieName.split(" 2x")[0]
        elif " 3x" in SerieName: SerieName = SerieName.split(" 3x")[0]
        elif " 4x" in SerieName: SerieName = SerieName.split(" 4x")[0]
        elif " 5x" in SerieName: SerieName = SerieName.split(" 5x")[0]
        elif " 6x" in SerieName: SerieName = SerieName.split(" 6x")[0]
        elif " 7x" in SerieName: SerieName = SerieName.split(" 7x")[0]
        elif " 8x" in SerieName: SerieName = SerieName.split(" 8x")[0]
        elif " 9x" in SerieName: SerieName = SerieName.split(" 9x")[0]

        SerieName = SerieName.strip()

        season = scrapertools.find_single_match(match, '<span class="season-desc">S(.*?)EP').strip()
        if not season: season = scrapertools.find_single_match(match, '<span class="season-desc">T(.*?)E').strip()

        if not season: season = 1

        epis = scrapertools.find_single_match(match, '<span class="season-desc">.*?EP(.*?)</span>').strip()
        if not epis: epis = scrapertools.find_single_match(match, '<span class="season-desc">.*?E(.*?)</span>').strip()

        if not epis: epis = 1

        titulo = title.replace('capitulo', '[COLOR goldenrod]Epis.[/COLOR]').replace('Capitulo', '[COLOR goldenrod]Epis.[/COLOR]').replace('episodio', '[COLOR goldenrod]Epis.[/COLOR]').replace('Episodio', '[COLOR goldenrod]Epis.[/COLOR]')

        titulo = str(season) + 'x' + str(epis) + ' ' + titulo.replace(str(season) + '×' + str(epis), '').strip()

        action = 'findvideos'

        if not item.group:
            action = 'temporadas'
            titulo = SerieName.capitalize()

            itemlist.append(item.clone( action = action, title = titulo, thumbnail = thumb, url = url, data_url = data_url,
                                        contentSerieName = SerieName, contentType = 'tvshow', infoLabels={'year': '-'} ))
        else:
            itemlist.append(item.clone( action = action, title = titulo, thumbnail = thumb, url = url, data_url = data_url,
                                        contentSerieName = SerieName, contentType = 'episode', contentSeason = season, contentEpisodeNumber = epis ))

    tmdb.set_infoLabels(itemlist)

    if itemlist:
        if '<div class="pagination">' in data:
            bloque = scrapertools.find_single_match(data, '<div class="pagination">(.*?)</main>')

            next_page = scrapertools.find_single_match(bloque, '<span class="current">.*?' + "href='(.*?)'")

            if next_page:
                if '/page/' in next_page:
                    itemlist.append(item.clone( title = 'Siguientes ...', url = next_page, action = 'last_epis', text_color = 'coral' ))

    return itemlist


def temporadas(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    temporadas = re.compile("data-snum='(.*?)'", re.DOTALL).findall(data)

    for tempo in temporadas:
        if not tempo: continue

        title = 'Temporada ' + tempo

        if len(temporadas) == 1:
            if config.get_setting('channels_seasons', default=True):
                platformtools.dialog_notification(item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'"), 'solo [COLOR tan]' + title + '[/COLOR]')

                item.page = 0
                item.contentType = 'season'
                item.contentSeason = tempo
                itemlist = episodios(item)
                return itemlist

        itemlist.append(item.clone( action = 'episodios', title = title, page = 0, contentType = 'season', contentSeason = tempo, text_color='tan' ))

    tmdb.set_infoLabels(itemlist)

    return itemlist


def episodios(item):
    logger.info()
    itemlist = []

    if not item.page: item.page = 0
    if not item.perpage: item.perpage = 50

    data = do_downloadpage(item.url)
    data = re.sub(r'\n|\r|\t|\s{2}|&nbsp;', '', data)

    bloque = scrapertools.find_single_match(data, "<ul id='season-listep-" + str(item.contentSeason) + "'.*?" + '(.*?)</ul>')

    patron = "href='(.*?)'.*?<img src='(.*?)'.*?alt='(.*?)'.*?<span class='ep-title'>(.*?)</span>"

    matches = re.compile(patron, re.DOTALL).findall(bloque)

    if item.page == 0 and item.perpage == 50:
        sum_parts = len(matches)

        try:
            tvdb_id = scrapertools.find_single_match(str(item), "'tvdb_id': '(.*?)'")
            if not tvdb_id: tvdb_id = scrapertools.find_single_match(str(item), "'tmdb_id': '(.*?)'")
        except: tvdb_id = ''

        if config.get_setting('channels_charges', default=True):
            item.perpage = sum_parts
            if sum_parts >= 100:
                platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando ' + str(sum_parts) + ' elementos[/COLOR]')
        elif tvdb_id:
            if sum_parts > 50:
                platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando Todos los elementos[/COLOR]')
                item.perpage = sum_parts
        else:
            item.perpage = sum_parts

            if sum_parts >= 1000:
                if platformtools.dialog_yesno(item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'"), '¿ Hay [COLOR yellow][B]' + str(sum_parts) + '[/B][/COLOR] elementos disponibles, desea cargarlos en bloques de [COLOR cyan][B]500[/B][/COLOR] elementos ?'):
                    platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando 500 elementos[/COLOR]')
                    item.perpage = 500

            elif sum_parts >= 500:
                if platformtools.dialog_yesno(item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'"), '¿ Hay [COLOR yellow][B]' + str(sum_parts) + '[/B][/COLOR] elementos disponibles, desea cargarlos en bloques de [COLOR cyan][B]250[/B][/COLOR] elementos ?'):
                    platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando 250 elementos[/COLOR]')
                    item.perpage = 250

            elif sum_parts >= 250:
                if platformtools.dialog_yesno(item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'"), '¿ Hay [COLOR yellow][B]' + str(sum_parts) + '[/B][/COLOR] elementos disponibles, desea cargarlos en bloques de [COLOR cyan][B]125[/B][/COLOR] elementos ?'):
                    platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando 125 elementos[/COLOR]')
                    item.perpage = 125

            elif sum_parts >= 125:
                if platformtools.dialog_yesno(item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'"), '¿ Hay [COLOR yellow][B]' + str(sum_parts) + '[/B][/COLOR] elementos disponibles, desea cargarlos en bloques de [COLOR cyan][B]75[/B][/COLOR] elementos ?'):
                    platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando 75 elementos[/COLOR]')
                    item.perpage = 75

            elif sum_parts > 50:
                if platformtools.dialog_yesno(item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'"), '¿ Hay [COLOR yellow][B]' + str(sum_parts) + '[/B][/COLOR] elementos disponibles, desea cargarlos [COLOR cyan][B]Todos[/B][/COLOR] de una sola vez ?'):
                    platformtools.dialog_notification('YandiSpoiler', '[COLOR cyan]Cargando ' + str(sum_parts) + ' elementos[/COLOR]')
                    item.perpage = sum_parts
                else: item.perpage = 50

    for url, thumb, epis, title in matches[item.page * item.perpage:]:
        epis = epis.replace('Episodio', '').replace('episodio', '').replace('Capitulo', '').replace('capitulo', '').strip()

        try:
            epis_i = int(epis)
        except:
            title_i = title.replace('Episodio', '').replace('episodio', '').replace('Capitulo', '').replace('capitulo', '').strip()

            try:
                epis_i = int(title_i)
                epis = epis_i
            except:
                epis = ''

        if not epis: epis = 1

        if item.search_type == 'movie': titulo = item.contentTitle
        else: titulo = str(item.contentSeason) + 'x' + str(epis) + ' ' + title + ' ' + item.contentSerieName.replace('&#038;', '&').replace('&#8217;', "'")

        titulo = titulo.replace('Season', '[COLOR tan]Temp.[/COLOR]').replace('season', '[COLOR tan]Temp.[/COLOR]')

        titulo = titulo.replace('Capitulo', '[COLOR goldenrod]Epis.[/COLOR]').replace('capitulo', '[COLOR goldenrod]Epis.[/COLOR]')

        titulo = titulo.replace('Episodio', '[COLOR goldenrod]Epis.[/COLOR]').replace('Episode', '[COLOR goldenrod]Epis.[/COLOR]').replace('episodio', '[COLOR goldenrod]Epis.[/COLOR]').replace('episode', '[COLOR goldenrod]Epis.[/COLOR]')

        itemlist.append(item.clone( action='findvideos', url = url, title = titulo,
                                    contentType = 'episode', contentSeason = item.contentSeason, contentEpisodeNumber=epis ))

        if len(itemlist) >= item.perpage:
            break

    tmdb.set_infoLabels(itemlist)

    if itemlist:
        if len(matches) > ((item.page + 1) * item.perpage):
            itemlist.append(item.clone( title="Siguientes ...", action="episodios", page = item.page + 1, perpage = item.perpage, text_color='coral' ))

    return itemlist


def findvideos(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    matches = re.compile("<li id='player-option-(.*?)</li>", re.DOTALL).findall(data)

    ses = 0

    for match in matches:
        dtype = scrapertools.find_single_match(match, "data-type='(.*?)'")
        dpost = scrapertools.find_single_match(match, "data-post='(.*?)'")
        dnume = scrapertools.find_single_match(match, "data-nume='(.*?)'")

        if not dtype or not dpost or not dnume: continue

        headers = {'Referer': item.url}

        post = {'action': 'zeta_player_ajax', 'post': dpost, 'nume': dnume, 'type': dtype}

        datap = do_downloadpage(host + 'wp-admin/admin-ajax.php', post = post, headers = headers)

        datap = datap.replace('=\\', '=').replace('\\"', '/"')

        datap = datap.replace('\\/', '/')

        url = scrapertools.find_single_match(datap, '<iframe.*?src="(.*?)".*?</iframe>')

        if url == '/': continue
        elif url == 'Pronto/': continue

        if url:
            ses += 1

            if '/short.' in url: continue
            elif '/boosterx.' in url: continue
            elif '/vectorx.' in url: continue
            elif '/ups2up.' in url: continue
            elif '/hgbazooka.' in url: continue
            elif '.tickcounter.' in url: continue
            elif '/zuvioeb.' in url: continue

            url = url.replace('/Mivalyo.com/', '/mivalyo.com/')

            servidor = servertools.get_server_from_url(url)

            servidor = servertools.corregir_servidor(servidor)

            if servertools.is_server_available(servidor):
                if not servertools.is_server_enabled(servidor): continue
            else:
                if not config.get_setting('developer_mode', default=False): continue

            lang = 'Vose'

            if '/es.' in match: lang = 'Esp'
            elif '/mx.' in match: lang = 'Lat'

            other = ''

            if not servidor == 'directo':
                if servidor == 'various': other = servertools.corregir_other(url)
                elif servidor == 'zures': other = servertools.corregir_zures(url)

            itemlist.append(Item( channel = item.channel, action = 'play', server = servidor, title = '', url = url, language = lang, other = other ))

    if not itemlist:
        if not ses == 0:
            platformtools.dialog_notification(config.__addon_name, '[COLOR tan][B]Sin enlaces Soportados[/B][/COLOR]')
            return

    return itemlist


def list_search(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    matches = re.compile('<div id="item-(.*?)</div> </div> </div></div>').findall(data)

    for match in matches:
        url = scrapertools.find_single_match(match, '<a href="(.*?)"')

        title = scrapertools.find_single_match(match, 'title="(.*?)"')

        if not url or not title: continue

        thumb = scrapertools.find_single_match(match, 'src="(.*?)"')

        title = title.replace('&#039;', '').replace('&#8217;', "'").replace('&#215;', ' ').strip()

        tipo = 'movie' if '/peliculas/' in url else 'tvshow'
        sufijo = '' if item.search_type != 'all' else tipo

        if tipo == 'movie':
            if not item.search_type == 'all':
                if item.search_type == 'tvshow': continue

            itemlist.append(item.clone( action='findvideos', url=url, title=title, thumbnail=thumb, fmt_sufijo=sufijo,
                                        contentType='movie', contentTitle=title, infoLabels={'year': '-'} ))

        if tipo == 'tvshow':
            if not item.search_type == 'all':
                if item.search_type == 'movie': continue

            data_url = scrapertools.find_single_match(match, 'data-url="(.*?)"')

            SerieName = data_url.replace('-', ' ').capitalize()

            itemlist.append(item.clone( action='temporadas', url=url, data_url = data_url, title=title, thumbnail=thumb, fmt_sufijo=sufijo, 
                                        contentSerieName = SerieName, contentType = 'tvshow', infoLabels={'year': '-'} ))

    tmdb.set_infoLabels(itemlist)

    if itemlist:
        if '<div class="pagination">' in data:
            bloque = scrapertools.find_single_match(data, '<div class="pagination">(.*?)</main>')

            next_page = scrapertools.find_single_match(bloque, '<span class="current">.*?' + "href='(.*?)'")

            if next_page:
                if '/page/' in next_page:
                    itemlist.append(item.clone( title = 'Siguientes ...', url = next_page, action = 'list_search', text_color = 'coral' ))

    return itemlist


def _epis(item):
    logger.info()

    item.url = host
    item.search_type = 'tvshow'

    return news_epis(item)


def search(item, texto):
    logger.info()
    try:
        item.url = host + '?s=' + texto.replace(" ", "+")
        return list_search(item)
    except:
        import sys
        for line in sys.exc_info():
            logger.error("%s" % line)
        return []
