from __future__ import print_function

import lxml.html, re, json
from lxml.html import fromstring

if __name__ == '__main__':
	import __init__
else:
	import logging
	log = logging.getLogger('main')

from decrypt import *
from utils import *

class jka:
	def __init__(self):
		log.debug('Module initiated')
		pass

	def search_anime(self, string, callback):
		search_text = re.sub(r'[^0-9a-z_\-!]', '', string.lower().replace(' ', '_'))
		content = None

		log.debug('Searching series for string "%s"' % string)
		try:
			html = get_content('http://jkanime.net/buscar/' + search_text + '/')
			content = fromstring(html)
		except BaseException as e:
			log.error('Could not retrieve search content for string "%s"' % search_text)
			log.error(e)
			return

		results = content.find_class('search')
		n_results = len(results[0].find_class('titl'))
		t_results = []

		if n_results > 0 :
			log.debug('Found %s results' % len(results))
			for anime in results:
				anchor = anime.find_class('titl')[0]
				name = anchor.text_content()
				url = anchor.attrib['href']
				t_results.append((name, url))
		else:
			log.warning('No results')
			msgbox('Alerta', 'Sin resultados')
		callback(t_results)

	def get_info(self, url, callback):
		try:
			log.info('Retrieving info from "%s"' % url)
			anime_html = get_content(url)
			dom = fromstring(anime_html)
		except BaseException as e:
			log.error('Could not retrieve anime info' % search_text)
			log.error(e)
			return

		# Get anime information
		info = {
			"name": dom.find_class('sinopsis_title')[0].text_content(),
			"description": dom.find_class('sinoptext')[0].find('p').text_content().strip(),
			"image_url": dom.find_class('descripbox')[0].find_class('separedescrip')[0].find('img').attrib['src'],
			"episodes": []
		}

		# Load episodes information
		pages_json = ''
		anime_id = text_finder(anime_html, 'social_counter/', '/')
		anime_cpages = len(dom.find_class('listpag'))

		if anime_cpages == 0:
			log.debug("Checking if it's an OVA")
			ltu = dom.find_class('lista_title_uniq')
			if len(ltu) > 0 and ltu[0].text_content() == 'OVA':
				info['episodes'].append(('OVA', url + 'ova/'))
			else:
				log.warning('No episodes available')
				msgbox('JKA Controller Error', 'No hay episodios disponibles para la serie!')
				callback(info)
				return
		else:
			# Retrieve all JSON content
			for i in range(anime_cpages):
				pages_json += get_content("http://jkanime.net/ajax/pagination_episodes/" + anime_id + "/" + str(i+1) + "/");

			# Decode JSON info about episodes
			# This could lead to a JSON error when it tries to decode an empty string
			try:
				pages_json = json.loads(pages_json.replace('][', ','))
			except ValueError as e:
				log.error(e)
				return

			for chapter in pages_json:
				info['episodes'].append((chapter['title'], url + chapter['number'] + '/'))

		log.debug('Anime: "%s", %s episodes' % (info['name'], len(info['episodes'])))
		return callback(info)

	def get_dd_link(self, url, callback = None):
		# La página de stream muestra varios "hosts" para elegir, en botones con la clase
		# "btn_show", y recorro estos botones buscando cual es el mejor. Sólo sirven los
		# hosts llamados "Ignition S" e "Ignition HD". El primero (supuestamente) estará
		# siempre disponible, pero si está "Ignition HD" disponible, se prefiere este.
		# Cada uno de estos botones se llama "#btn-show-N", donde N es un número vinculado
		# a un div de "#the_video-N", del cual se obtiene la URL del episodio a descargar.
		download_link = ''
		raw_links = {'propietary': ''}

		try:
			log.debug('Retrieving content from url "%s"' % url)
			html = get_content(url)
			dom = fromstring(html)
		except TypeError as e:
			log.error('Could not retrieve content from url ' + url)
			log.error(e)
			return

		for opt in dom.find_class('btn-show'):
			n = opt.attrib['id'][-1]
			host = opt.text_content().strip().lower()

			if host == 'ignition hd' or (host == 'ignition s' and raw_links['propietary'] == ''):
				log.debug('Found propietary host "%s"' % host)
				obj = dom.get_element_by_id('the_video-' + n).find('object')
				param = obj.xpath("param[@name='flashvars']")[0]
				raw_links['propietary'] = text_finder(param.attrib['value'], 'file=', '&')

			if host == 'dailymotion':
				log.debug('Found "%s"' % host)
				obj = dom.get_element_by_id('the_video-' + n).find('iframe')
				raw_links[host] = obj.attrib['src']

		download_link = best_link(raw_links)

		if download_link != '': log.debug('Download link retrieved: ' + download_link)
		else: log.warning('Could not retrieve any download link')
		if callback != None: callback(download_link)

# Test cases
if __name__ == "__main__":
	log = create_logger()
	do_tests(jka)