# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para PelisDanko
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------

import re
import sys

from core import config
from core import logger
from core import scrapertools
from core.item import Item


__modo_grafico__ = config.get_setting('modo_grafico', 'pelisdanko')

DEBUG = config.get_setting("debug")
host = "http://pelisdanko.com"
art = "http://pelisdanko.com/img/background.jpg"


def mainlist(item):
    logger.info("pelisalacarta.channels.pelisdanko mainlist")

    itemlist = []
    itemlist.append(item.clone(action="novedades", title="Novedades", url=host + "/novedades",
                               fanart=art))
    itemlist.append(item.clone(action="novedades", title="Estrenos", url=host + "/estrenos",
                               fanart=art))
    itemlist.append(item.clone(action="novedades", title="Populares", url=host + "/populares",
                               fanart=art))
    itemlist.append(item.clone(action="actualizadas", title="Películas actualizadas", url=host,
                               fanart=art))
    itemlist.append(item.clone(action="indices", title="Índices", fanart=art))
    itemlist.append(item.clone(title="", action=""))
    itemlist.append(item.clone(action="search", title="Buscar...", fanart=art))

    itemlist.append(item.clone(action="configuracion", title="Configurar canal...", fanart=art,
                               text_color="gold", folder=False))

    return itemlist


def configuracion(item):
    from platformcode import platformtools
    ret = platformtools.show_channel_settings()
    platformtools.itemlist_refresh()
    return ret


def search(item, texto):
    logger.info("pelisalacarta.channels.pelisdanko search")
    texto = texto.replace(" ", "+")
    item.url = "http://pelisdanko.com/busqueda?terms=%s" % texto
    try:
        return novedades(item)
    # Se captura la excepción, para no interrumpir al buscador global si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("%s" % line)
        return []


def newest(categoria):
    logger.info("pelisalacarta.channels.pelisdanko newest")
    itemlist = []
    item = Item()
    try:
        if categoria == 'peliculas':
            item.url = "http://pelisdanko.com/novedades"
            itemlist = novedades(item)

            if itemlist[-1].action == "novedades":
                itemlist.pop()

    # Se captura la excepción, para no interrumpir al canal no
vedades si un canal falla
    except:
        import sys
        for line in sys.exc_info():
            logger.error("{0}".format(line))
        return []

    return itemlist


def novedades(item):
    logger.info("pelisalacarta.channels.pelisdanko novedades")
    iteml
ist = []

    # Descarga la pagina
    data = scrapertools.downloadpage(item.url)
    bloque = scrapertools.find_multiple_matches(data, '<div class="col-xs-[\d] col-sm-[\d] col-md-[\d] col-lg-[\d]'
                                                      ' text-center"(.*?)</div>')

    for match in bloque:
        calidades = scrapertools.find_multiple_matches(match, '<span class="badge badge-critic badge-qualities[^>]+>'
                                                              '([^<]+)</span>')
        calidad = "[COLOR darkseagreen]   "
        for quality in calidades:
            calidad += "[" + quality + "]"
        patron = 'title="([^"]+)".*?href="([^"]+)".*?class="img-responsive img-thumbnail" src="([^"]+)"'
        matches = scrapertools.find_multiple_matches(match, patron)
        for scrapedtitle, scrapedurl, scrapedthumbnail in matches:
            contentTitle = scrapedtitle[:]
            scrapedtitle = "[COLOR darkorange][B]" + scrapedtitle + "[/B][/COLOR]" + calidad + "[/COLOR]"
            if (DEBUG): logger.info(
                    "title=[" + scrapedtitle + "], url=[" + scrapedurl + "], thumbnail=[" + scrapedthumbnail + "]")
            itemlist.append(item.clone(action="enlaces", title=bbcode_kodi2html(scrapedtitle),
                                       url=scrapedurl, thumbnail=scrapedthumbnail, fanart=scrapedthumbnail,
                                       fulltitle=contentTitle, filtro=False, contentTitle=contentTitle,
                                       context=["buscar_trailer"], contentType="movie", trailer=True))

    # Busca enlaces de paginas siguientes...
    next_page_url = scrapertools.find_single_match(data, '<a href="([^"]+)" rel="next">')
    if len(next_page_url) > 0:
        itemlist.append(item.clone(action="novedades", title=">> Página siguiente", url=next_page_url))

    return itemlist


def actualizadas(item):
    logger.info("pelisalacarta.channels.pelisdanko actualizadas")
    itemlist = []

    # Descarga la pagina
    data = scrapertools.downloadpage(item.url)
    bloque_big = scrapertools.find_single_match(data, 'Últimas actualizaciones(.*?)<div class="col-xs-10 col-md-8 '
                                                      'text-left">')
    bloque = scrapertools.find_multiple_matches(bloque_big, '<div class="col-xs-[\d] col-sm-[\d] col-md-[\d]'
                                                            ' col-lg-[\d] text-center"(.*?)<br><br>')

    for match in bloque:
        calidades = scrapertools.find_multiple_matches(match, '<span class="badge badge-critic badge-qualities[^>]+>'
                                                              '([^<]+)</span>')
        calidad = "[COLOR darkseagreen]  "
        for quality in calidades:
            calidad += "[" + quality + "]"
        languages = scrapertools.find_multiple_matches(match, '<img width="28".*?alt="([^"]+)"')
        idiomas = "  ("
        for idioma in languages:
            idioma = idioma.replace('ES_', '').replace('ES', 'CAST')
            if idioma != "CAST" and idioma != "LAT":
                idioma = "VOSE"
            idiomas += idioma + "/"
        patron = 'title="([^"]+)".*?href="([^"]+)".*?class="img-responsive img-thumbnail" src="([^"]+)"'
        matches = scrapertools.find_multiple_matches(match, patron)
        for scrapedtitle, scrapedurl, scrapedthumbnail in matches:
            contentTitle = scrapedtitle[:]
            scrapedtitle = "[COLOR darkorange][B]" + scrapedtitle + "[/B][/COLOR]" + calidad + idiomas[
                                                                                               :-1] + ")[/COLOR]"
            if (DEBUG): logger.info(
                    "title=[" + scrapedtitle + "], url=[" + scrapedurl + "], thumbnail=[" + scrapedthumbnail + "]")
            itemlist.append(item.clone(action="enlaces", title=bbcode_kodi2html(scrapedtitle),
                                       url=scrapedurl, thumbnail=scrapedthumbnail, fanart=scrapedthumbnail,
                                       fulltitle=contentTitle, filtro=False, contentTitle=contentTitle,
                                       context=["buscar_trailer"], contentType="movie"))

    return itemlist


def indices(item):
    logger.info("pelisalacarta.channels.pelisdanko indices")
    itemlist = []

    item.text_color = "orchid"
    itemlist.append(item.clone(action="indice_list", title="Género", url=host, fulltitle="genero"))
    itemlist.append(item.clone(action="indice_list", title="Alfabético", url=host, fulltitle="letra"))
    itemlist.append(item.clone(action="indice_list", title="Idioma", url=host, fulltitle="idioma"))
    itemlist.append(item.clone(action="indice_list", title="Calidad", url=host, fulltitle="calidad"))
    itemlist.append(item.clone(action="indice_list", title="Nacionalidad", url=host, fulltitle="nacionalidad"))

    return itemlist


def indice_list(item):
    logger.info("pelisalacarta.channels.pelisdanko indice_list")
    itemlist = []
    # Descarga la pagina
    data = scrapertools.downloadpage(item.url)

    patron = '<a href="(http://pelisdanko.com/%s/[^"]+)">([^<]+)</a>' % item.fulltitle
    matches = scrapertools.find_multiple_matches(data, patron)
    for scrapedurl, scrapedtitle in matches:
       