import sys
from queue import SimpleQueue
from threading import Thread
from indexers import mdblist_api
from menus.movies import Movies
from menus.tvshows import TVShows
from modules import kodi_utils
from modules.utils import paginate_list, TaskPool, get_max_threads
from modules.list_sorting import apply_context_list_sort
from modules.settings import paginate, page_limit, nav_jump_use_alphabet
# logger = kodi_utils.logger

KODI_VERSION, ls = kodi_utils.get_kodi_version(), kodi_utils.local_string
build_url, make_listitem = kodi_utils.build_url, kodi_utils.make_listitem
fanart = ''
default_icon = kodi_utils.media_path('mdblist.png')
item_jump = kodi_utils.media_path('item_jump.png')
copy2str = ls(33147)

# Export vers TMDb seulement si le compte TMDb est autorisé dans alkoFlix.
def tmdb_export_available():
	return kodi_utils.get_setting('tmdb.account_id') not in ('', None)
nextpage_str, jump2_str, mdblist_str = ls(32799), ls(32964), 'MDBList'
def _list_favourite_context(url_params, name):
	fav_params = dict(url_params or {})
	fav_params['target_mode'] = fav_params.get('mode')
	fav_params.update({'mode': 'favourites_choice', 'media_type': 'list', 'fav_type': 'list', 'list_service': 'mdblist', 'title': name, 'name': name})
	return ('Favoris (alkoFlix)', 'RunPlugin(%s)' % build_url(fav_params))


def search_mdbl_lists(params):
	def _process():
		for item in lists:
			try:
				cm = []
				cm_append = cm.append
				name, user, slug, list_id = item['name'], item['user_name'], item['slug'], item['id']
				likes, item_count = item['likes'] or 0, item.get('items', '?')
				display = '%s (x%s) - %s' % (name, str(item_count), user)
				plot = 'Likes: %s' % likes
				url_params = {'mode': 'build_mdb_list', 'user': user, 'slug': slug, 'list_id': list_id, 'name': name}
				media_filter = params.get('media_filter')
				if media_filter: url_params['media_filter'] = media_filter
				url = build_url(url_params)
				cm[:0] = kodi_utils.menu_editor_context(url_params, name, default_icon) + kodi_utils.list_sort_context(url_params, name, default_icon)
				cm_append(_list_favourite_context(url_params, name))
				tmdb_export_available() and cm_append((copy2str, 'RunPlugin(%s)' % build_url({'mode': 'tmdb_manager_choice', 'mdbl_list_id': list_id, 'mdbl_list_name': name, 'user': user, 'list_slug': slug})))
				listitem = make_listitem()
				listitem.setLabel(display)
				listitem.setArt({'icon': default_icon, 'poster': default_icon, 'thumb': default_icon, 'fanart': fanart, 'banner': default_icon})
				listitem.setInfo('video', {'plot': plot}) if KODI_VERSION < 20 else listitem.getVideoInfoTag().setPlot(plot)
				listitem.addContextMenuItems(cm)
				yield (url, listitem, True)
			except: pass
	page = params.get('new_page', '1')
	search_title = params.get('search_title') or kodi_utils.dialog.input('alkoFlix')
	if search_title: lists, pages = mdblist_api.mdbl_searchlists(search_title), '1'
	else: lists, pages = [], page
	if not lists: lists = []
	__handle__ = int(sys.argv[1])
	kodi_utils.add_items(__handle__, list(_process()))
	if int(pages) > int(page):
		url = {'mode': 'build_mdb_list.search_mdbl_lists', 'search_title': search_title, 'new_page': int(page) + 1}
		if params.get('media_filter'): url['media_filter'] = params.get('media_filter')
		kodi_utils.add_dir(__handle__, url, nextpage_str)
	kodi_utils.set_category(__handle__, search_title)
	kodi_utils.set_content(__handle__, 'files')
	kodi_utils.end_directory(__handle__)
	kodi_utils.set_view_mode('view.main')

def get_mdbl_lists(params):
	def _process():
		for item in lists:
			try:
				cm = []
				cm_append = cm.append
				list_type = 'external' if 'source' in item else 'user_lists'
				name, user, list_id = item['name'], item['user_name'], item['id']
				slug, likes, item_count = item.get('slug', ''), item.get('likes', 0), item.get('items', '?')
				display = '%s (x%s)' % (name, item_count) if item_count else name
				plot = 'Likes: %s' % likes if likes else ''
				url_params = {'mode': 'build_mdb_list', 'user': user, 'slug': slug, 'list_id': list_id, 'list_type': list_type, 'name': name}
				media_filter = params.get('media_filter')
				if media_filter: url_params['media_filter'] = media_filter
				url = build_url(url_params)
				cm[:0] = kodi_utils.menu_editor_context(url_params, name, default_icon) + kodi_utils.list_sort_context(url_params, name, default_icon)
				cm_append(_list_favourite_context(url_params, name))
				tmdb_export_available() and cm_append((copy2str, 'RunPlugin(%s)' % build_url({'mode': 'tmdb_manager_choice', 'mdbl_list_id': list_id, 'mdbl_list_name': name, 'user': user, 'list_slug': slug})))
				listitem = make_listitem()
				listitem.setLabel(display)
				listitem.setArt({'icon': default_icon, 'poster': default_icon, 'thumb': default_icon, 'fanart': fanart, 'banner': default_icon})
				listitem.setInfo('video', {'plot': plot}) if KODI_VERSION < 20 else listitem.getVideoInfoTag().setPlot(plot)
				listitem.addContextMenuItems(cm, replaceItems=False)
				yield (url, listitem, True)
			except: pass
	lists = []
	lists += mdblist_api.mdbl_userlists()
	lists += mdblist_api.mdbl_externallists()
	__handle__ = int(sys.argv[1])
	kodi_utils.add_items(__handle__, list(_process()))
	kodi_utils.set_category(__handle__, params.get('name'))
	kodi_utils.set_sort_method(__handle__, 'label')
	kodi_utils.set_content(__handle__, 'files')
	kodi_utils.end_directory(__handle__)
	kodi_utils.set_view_mode('view.main')

def get_mdbl_toplists(params):
	def _process():
		for item in lists:
			try:
				cm = []
				cm_append = cm.append
				name, user, slug, list_id = item['name'], item['user_name'], item['slug'], item['id']
				likes, item_count = item['likes'], item.get('items', '?')
				display = '%s (x%s) - %s' % (name, item_count, user)
				plot = 'Likes: %s' % likes
				url_params = {'mode': 'build_mdb_list', 'user': user, 'slug': slug, 'list_id': list_id, 'name': name}
				media_filter = params.get('media_filter')
				if media_filter: url_params['media_filter'] = media_filter
				url = build_url(url_params)
				cm[:0] = kodi_utils.menu_editor_context(url_params, name, default_icon) + kodi_utils.list_sort_context(url_params, name, default_icon)
				cm_append(_list_favourite_context(url_params, name))
				tmdb_export_available() and cm_append((copy2str, 'RunPlugin(%s)' % build_url({'mode': 'tmdb_manager_choice', 'mdbl_list_id': list_id, 'mdbl_list_name': name, 'user': user, 'list_slug': slug})))
				listitem = make_listitem()
				listitem.setLabel(display)
				listitem.setArt({'icon': default_icon, 'poster': default_icon, 'thumb': default_icon, 'fanart': fanart, 'banner': default_icon})
				listitem.setInfo('video', {'plot': plot}) if KODI_VERSION < 20 else listitem.getVideoInfoTag().setPlot(plot)
				listitem.addContextMenuItems(cm)
				yield (url, listitem, True)
			except: pass
	lists = mdblist_api.mdbl_toplists()
	__handle__ = int(sys.argv[1])
	kodi_utils.add_items(__handle__, list(_process()))
	kodi_utils.set_category(__handle__, params.get('name'))
	kodi_utils.set_content(__handle__, 'files')
	kodi_utils.end_directory(__handle__)
	kodi_utils.set_view_mode('view.main')

def build_mdb_list(params):
	def _thread_target(q):
		while not q.empty():
			try: target, *args = q.get()
			except: pass
			else: target(*args)
	__handle__, _queue, is_widget = int(sys.argv[1]), SimpleQueue(), kodi_utils.external_browse()
	max_threads = get_max_threads()
	use_alphabet = nav_jump_use_alphabet() > 0
	user, slug, name = params.get('user'), params.get('slug'), params.get('name')
	list_type, list_id = params.get('list_type'), params.get('list_id')
	letter, page = params.get('new_letter', 'None'), int(params.get('new_page', '1'))
	results = mdblist_api.mdbl_list_items(list_id, list_type) or []
	media_filter = params.get('media_filter')
	if media_filter == 'movie': results = [i for i in results if i.get('mediatype') == 'movie']
	elif media_filter == 'tvshow': results = [i for i in results if i.get('mediatype') == 'show']
	results = apply_context_list_sort(results, 'mdblist', params)
	if paginate() and results: process_list, total_pages = paginate_list(results, page, letter, page_limit())
	else: process_list, total_pages = results, 1
	exclude_animation = 'true' if media_filter in ('movie', 'tvshow') else 'false'
	movies, tvshows = Movies({'id_type': 'trakt_dict', 'exclude_animation': exclude_animation}), TVShows({'id_type': 'trakt_dict', 'exclude_animation': exclude_animation})
	for idx, tag in enumerate(process_list, 1):
		mtype = tag['mediatype']
		if   mtype == 'movie':
			_queue.put((movies.build_movie_content, idx, {'imdb': tag['imdb_id'], 'tmdb': tag['id']}))
		elif mtype == 'show':
			_queue.put((tvshows.build_tvshow_content, idx, {'imdb': tag['imdb_id'], 'tmdb': tag['id']}))
	max_threads = min(_queue.qsize(), max_threads)
	threads = (Thread(target=_thread_target, args=(_queue,)) for i in range(max_threads))
	threads = list(TaskPool.process(threads))
	[i.join() for i in threads]
	items = movies.items + tvshows.items
	items.sort(key=lambda k: int(k[1].getProperty('alkoflix_sort_order')))
	if media_filter == 'movie':
		content = 'movies'
	elif media_filter == 'tvshow':
		content = 'tvshows'
	else:
		content, total = max(
			('movies', movies), ('tvshows', tvshows), key=lambda k: len(k[1].items)
		)
	if total_pages > 2 and not is_widget and use_alphabet:
		url = {'mode': 'build_navigate_to_page', 'current_page': page, 'total_pages': total_pages,
				'user': user, 'slug': slug, 'name': name, 'list_id': list_id, 'list_type': list_type,
				'transfer_mode': 'build_mdb_list', 'media_type': 'Media', 'media_filter': media_filter}
		if params.get('list_sort'): url['list_sort'] = params.get('list_sort')
		if params.get('list_random_seed'): url['list_random_seed'] = params.get('list_random_seed')
		if params.get('regional_filter'): url['regional_filter'] = params.get('regional_filter')
		kodi_utils.add_dir(__handle__, url, jump2_str, iconImage=item_jump, isFolder=False)
	kodi_utils.add_items(__handle__, items)
	if total_pages > page:
		url = {'mode': 'build_mdb_list', 'new_page': page + 1, 'new_letter': letter,
				'user': user, 'slug': slug, 'name': name, 'list_id': list_id, 'list_type': list_type}
		if media_filter: url['media_filter'] = media_filter
		if params.get('list_sort'): url['list_sort'] = params.get('list_sort')
		if params.get('list_random_seed'): url['list_random_seed'] = params.get('list_random_seed')
		if params.get('regional_filter'): url['regional_filter'] = params.get('regional_filter')
		kodi_utils.add_dir(__handle__, url, nextpage_str)
	kodi_utils.set_category(__handle__, name)
	kodi_utils.set_content(__handle__, content)
	kodi_utils.end_directory(__handle__, False if is_widget else None)
	kodi_utils.set_view_mode('view.%s' % content, content)

def mdbl_account_info():
	try:
		kodi_utils.show_busy_dialog()
		account_info = mdblist_api.call_mdblist('user')
		api_requests = account_info['api_requests']
		remaining = api_requests - account_info['api_requests_count']
		body = []
		append = body.append
		append('Username: %s' % account_info['username'])
		append('Supporter: %s' % account_info['is_supporter'])
		append('API Request Limit: %s' % api_requests)
		append('API Request Remaining: %s' % remaining)
		kodi_utils.hide_busy_dialog()
		return kodi_utils.show_text(mdblist_str.upper(), '\n\n'.join(body), font_size='large')
	except: kodi_utils.hide_busy_dialog()

