import sys
import json
from urllib.parse import unquote
from datetime import timedelta
from caches.main_cache import MainCache
from modules import kodi_utils, settings
# from modules.kodi_utils import logger

ls, build_url, make_listitem = kodi_utils.local_string, kodi_utils.build_url, kodi_utils.make_listitem
search_icon = kodi_utils.media_path('recent.png')
default_icon = kodi_utils.media_path('search.png')
remove_str, search_str, hist_str = ls(32786), ls(32450), ls(32486)
mov_str, tv_str, peop_str, coll_str, easy_str = ls(32028), ls(32029), ls(32507), ls(32499), ls(32070)
kw_mov_str, kw_tv_str = 'Mot-clé TMDb (%s)' % mov_str, 'Mot-clé TMDb (%s)' % tv_str
new_search_str = 'Nouvelle recherche...'

def _clear_history_label(label):
	return "Supprimer l'historique de recherche (%s)" % label

mode_dict, clear_history_list = {
	'movie': ('movie_queries', {'mode': 'get_search_term', 'media_type': 'movie'}),
	'tvshow': ('tvshow_queries', {'mode': 'get_search_term', 'media_type': 'tv_show'}),
	'people': ('people_queries', {'mode': 'get_search_term', 'search_type': 'people'}),
	'tmdb_collections': ('tmdb_collections_queries', {'mode': 'get_search_term', 'search_type': 'tmdb_collections', 'media_type': 'movie'}),
	'tmdb_keyword_movie': ('tmdb_keyword_movie_queries', {'mode': 'get_search_term', 'search_type': 'tmdb_keyword', 'media_type': 'movie'}),
	'tmdb_keyword_tvshow': ('tmdb_keyword_tvshow_queries', {'mode': 'get_search_term', 'search_type': 'tmdb_keyword', 'media_type': 'tvshow'}),
	'easynews_video': ('easynews_video_queries', {'mode': 'get_search_term', 'search_type': 'easynews_video'})
}, {
	'movie_queries': _clear_history_label(mov_str),
	'tvshow_queries': _clear_history_label(tv_str),
	'people_queries': _clear_history_label(peop_str),
	'tmdb_collections_queries': _clear_history_label('Collections TMDb'),
	'tmdb_keyword_movie_queries': _clear_history_label(kw_mov_str),
	'tmdb_keyword_tvshow_queries': _clear_history_label(kw_tv_str),
	'easynews_video_queries': _clear_history_label(easy_str)
}

def search_history(params):
	def _builder():
		for query in contents:
			try:
				cm = []
				url_params['query'] = query
				display = '[B]%s :[/B] %s' % (hist_str, query)
				url = build_url(url_params)
				cm.append((remove_str, 'RunPlugin(%s)' % build_url({'mode': 'remove_from_history', 'setting_id': setting_id, 'query': query})))
				listitem = make_listitem()
				listitem.setLabel(display)
				listitem.setArt({'icon': search_icon, 'poster': search_icon, 'thumb': search_icon, 'fanart': fanart, 'banner': search_icon})
				listitem.addContextMenuItems(cm)
				yield (url, listitem, False)
			except: pass
	__handle__, fanart = int(sys.argv[1]), settings.addon_fanart()
	setting_id, action_dict = mode_dict[params['action']]
	url_params = dict(action_dict)
	if params.get('action') == 'tmdb_collections':
		for key in ('saga_type', 'fav_type'):
			if params.get(key): url_params[key] = params.get(key)
	kodi_utils.add_dir(__handle__, url_params, new_search_str, iconImage=default_icon, isFolder=False)
	contents = MainCache().get(setting_id)
	if contents: kodi_utils.add_items(__handle__, list(_builder()))
	kodi_utils.set_category(__handle__, params.get('name'))
	kodi_utils.set_content(__handle__, '')
	kodi_utils.end_directory(__handle__)
	kodi_utils.set_view_mode('view.main', '')

def get_search_term(params):
	kodi_utils.close_all_dialog()
	media_type = params.get('media_type', '')
	search_type = params.get('search_type', 'media_title')
	params_query = params.get('query', '')
	if search_type == 'people':
		url_params, string = {'mode': 'person_search'}, 'people_queries'
	elif search_type == 'tmdb_keyword':
		url_params, string = {'mode': 'tmdb_build_keyword_results', 'media_type': media_type}, 'tmdb_keyword_%s_queries' % media_type
	elif search_type == 'easynews_video':
		url_params, string = {'mode': 'easynews.search_easynews'}, 'easynews_video_queries'
	elif search_type == 'tmdb_collections':
		url_params, string = {'mode': 'build_movie_list', 'action': 'tmdb_movies_search_collections'}, 'tmdb_collections_queries'
		for key in ('saga_type', 'fav_type'):
			if params.get(key): url_params[key] = params.get(key)
	else:
		if media_type == 'movie': url_params, string = {'mode': 'build_movie_list', 'action': 'tmdb_movies_search'}, 'movie_queries'
		else: url_params, string = {'mode': 'build_tvshow_list', 'action': 'tmdb_tv_search'}, 'tvshow_queries'
	query = params_query or kodi_utils.dialog.input('alkoFlix')
	if not query.strip(): return
	query = unquote(query)
	add_to_search_history(query, string)
	url_params['query'] = query
	if kodi_utils.external_browse():
		return kodi_utils.execute_builtin('ActivateWindow(Videos,%s,return)' % kodi_utils.build_url(url_params))
	return kodi_utils.execute_builtin('Container.Update(%s)' % kodi_utils.build_url(url_params))

def add_to_search_history(search_name, search_list):
	try:
		result = []
		maincache = MainCache()
		cache = maincache.get(search_list)
		if cache: result = cache
		if search_name in result: result.remove(search_name)
		result.insert(0, search_name)
		result = result[:50]
		maincache.set(search_list, result, expiration=timedelta(days=365))
	except: pass


def add_direct_search_to_history(params):
	try:
		# Les recherches lancées par un skin arrivent directement sur les routes
		# de résultats avec query=... et ne passent pas par get_search_term().
		# On les ajoute donc ici à l'historique alkoFlix, uniquement pour la
		# première page afin de ne pas réécrire l'historique à chaque pagination.
		if str(params.get('new_page', '1')) not in ('', '1'): return
		mode = params.get('mode', '')
		action = params.get('action', '')
		search_list = ''
		query = params.get('query', '')
		if mode == 'build_movie_list':
			if action == 'tmdb_movies_search': search_list = 'movie_queries'
			elif action == 'tmdb_movies_search_collections': search_list = 'tmdb_collections_queries'
		elif mode == 'build_tvshow_list':
			if action == 'tmdb_tv_search': search_list = 'tvshow_queries'
		elif mode == 'tmdb_build_keyword_results':
			media_type = params.get('media_type', '')
			if media_type in ('movie', 'tvshow'):
				search_list = 'tmdb_keyword_%s_queries' % media_type
		elif mode == 'person_search':
			search_list = 'people_queries'
		if not search_list or not query or not query.strip(): return
		add_to_search_history(unquote(query).strip(), search_list)
	except: pass

def remove_from_search_history(params):
	try:
		maincache = MainCache()
		result = maincache.get(params['setting_id'])
		result.remove(params.get('query'))
		maincache.set(params['setting_id'], result, expiration=timedelta(days=365))
		kodi_utils.notification(32576)
		kodi_utils.container_refresh()
	except: pass

def clear_search_history():
	try:
		available_history = dict(clear_history_list)
		# N'affiche pas l'historique Easynews si aucun compte Easynews n'est actif.
		if not settings.easynews_active():
			available_history.pop('easynews_video_queries', None)
		list_items = [{'line1': item, 'icon': search_icon} for item in available_history.values()]
		kwargs = {'items': json.dumps(list_items), 'heading': hist_str}
		setting = kodi_utils.select_dialog(list(available_history.keys()), **kwargs)
		if setting is None: return
		MainCache().delete(setting)
		kodi_utils.notification(32576)
	except: pass


def tmdb_keyword_help():
	return kodi_utils.show_text('alkoFlix Recherche - %s' % ls(32487), tmdb_keyword_help_text)

tmdb_keyword_help_text = (
"""
[B]RECHERCHE PAR MOT-CLÉ TMDb[/B]

La recherche par mot-clé utilise les mots-clés référencés directement sur TMDb.

Petit détail important : la majorité de ces mots-clés sont enregistrés en anglais sur TMDb, même lorsque le film ou la série existe en français.

[B]Conseil[/B]
Utilisez de préférence un mot-clé anglophone.

[B]Exemples[/B]
- [B]Famille[/B] peut ne donner aucun résultat
- [B]Family[/B] retourne beaucoup plus de résultats

Autres exemples utiles :
- [B]Christmas[/B] au lieu de Noël
- [B]Revenge[/B] au lieu de vengeance
- [B]Time travel[/B] au lieu de voyage dans le temps
- [B]Superhero[/B] au lieu de super-héros

Ce n’est pas un bug d’alkoFlix : c’est simplement la façon dont les mots-clés sont majoritairement référencés dans TMDb.
"""
)

