# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import cookielib
import urlparse,urllib2,urllib,re
import os
import sys

from core import logger
from core import config
from core import scrapertools
from core.item import Item
from servers import servertools
import urllib

__channel__ = "chat"
__category__ = "F"
__type__ = "generic"
__title__ = "chat"
__language__ = "ES"
__adult__ = "true"

DEBUG = config.get_setting("debug")

def isGeneric():
    return True

def mainlist(item):
    logger.info("[chat.py] mainlist")
    itemlist = []
    itemlist.append( Item(channel=__channel__, action="videos"    , title="Female" , url="http://www.chaturbate.com/female-cams"))
    itemlist.append( Item(channel=__channel__, action="videos"    , title="Male" , url="http://www.chaturbate.com/male-cams"))
    itemlist.append( Item(channel=__channel__, action="videos"    , title="Couples" , url="http://www.chaturbate.com/couple-cams"))
    itemlist.append( Item(channel=__channel__, action="videos"    , title="Transsexual" , url="http://www.chaturbate.com/transsexual-cams"))
    
    return itemlist

# REALMENTE PASA LA DIRECCION DE BUSQUEDA

def search(item,texto):
    logger.info("[chat.py] search")
    tecleado = texto.replace( " ", "+" )
    item.url = item.url % tecleado
    return videos(item)

# SECCION ENCARGADA DE BUSCAR

def videos(item):
    logger.info("[chat.py] videos")
    # <div id="movies" style="width: 100%; ">
    data = scrapertools.downloadpageGzip(item.url)
    itemlist = [] 
    matches = re.compile(r"""<div class='list'>.*?</div>.*?</ul></div></li>""",re.DOTALL).findall(data)
    for match in matches:
        datos = re.compile(r"""<div class='list'>.*?</div>""", re.S).findall(match)
        for vid in datos:
            aRef = re.compile(r"""<img src="([^"]+)"><a href="([^"]+)" alt="([^"]+)""", re.S).findall(vid)
            video = aRef[1]
            scrapedtitle = video[2]
            scrapedurl =  urlparse.urljoin( "http://www.chaturbate.com/", video[1] )
            scrapedthumbnail = urlparse.urljoin( "http://www.chaturbate.com/", video[0] )
            scrapedplot = ""
            # Depuracion
            if (DEBUG): logger.info("title=["+scrapedtitle+"], url=["+scrapedurl+"], thumbnail=["+scrapedthumbnail+"]")            
            itemlist.append( Item(channel=__channel__, action="video" , title=scrapedtitle , url=scrapedurl, thumbnail=scrapedthumbnail, plot=scrapedplot, show=scrapedtitle))
    return itemlist

# SECCION ENCARGADA DE VOLCAR EL LISTADO DE CATEGORIAS CON EL LINK CORRESPONDIENTE A CADA PAGINA
    
def listcategorias(item):
    logger.info("[chat.py] listcategorias")
    itemlist = []
    return itemlist
    

# OBTIENE LOS ENLACES SEGUN LOS PATRONES DEL VIDEO Y LOS UNE CON EL SERVIDOR
def video(item):
    logger.info("[chat.py] play")
    data = scrapertools.downloadpage(item.url)
    itemlist = []
    matches = re.compile('so.addVariable\("file", "([^"]+)"\);', re.DOTALL).findall(data)
    if len(matches)>0:
        parsed_url = urllib.unquote_plus(matches[0])
        print parsed_url
        paginador = Item(channel=__channel__, action="play" , title=item.title, fulltitle=item.fulltitle , url=parsed_url, thumbnail=item.thumbnail, plot=item.plot, show=item.title, server="directo", folder=False)
    else:
        paginador = None
    
    if paginador is not None:
        itemlist.append( paginador )

    return itemlist

