# -*- coding: utf-8 -*-
# plugin.video.alkoflix
# resources/lib/router.py

import sys
from modules.kodi_utils import parse_qsl, logger, get_property, get_infolabel, external_browse, end_directory, notification

def runmode(cls, params, mode):
	call = getattr(cls(params), mode, None)
	return call() if callable(call) else None

class Router:
	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_value, traceback):
		if get_property('alkoflix_rli_fix') == 'true' and external_browse():
			message = f"alkoflix not in '{get_infolabel('Container.PluginName')}'"
			raise SystemExit(message)

	def routing(self, sys):
		try: params = dict(parse_qsl(sys.argv[2][1:]))
		except Exception as e: return logger('routing error', str(e))

		params_get = params.get
		mode = params_get('mode', 'navigator.main')
		try:
			from menus.history import add_direct_search_to_history
			add_direct_search_to_history(params)
		except Exception as e: logger('direct search history skipped', str(e))
		if 'navigator.' in mode:
			from menus.navigator import Navigator
			runmode(Navigator, params, mode.split('.')[1])
		elif 'menu_editor.' in mode:
			from modules.menu_editor import MenuEditor
			runmode(MenuEditor, params, mode.split('.')[1])
		elif 'discover.' in mode:
			from menus.discover import Discover
			runmode(Discover, params, mode.split('.')[1])
		elif 'catalogue.' in mode:
			from catalogue.catalogs import Catalogues
			runmode(Catalogues, params, mode.split('.')[1])
		elif 'people.' in mode:
			from menus.people import PeopleMenu
			runmode(PeopleMenu, params, mode.split('.')[1])
		elif mode == 'media_play':
			from modules.kodi_utils import player, close_all_dialog
			close_all_dialog()
			player.play(params['url'])
		elif mode == 'play_media':
			from modules.sources import SourceSelect
			SourceSelect.factory(params)
		elif mode in ('parental_pin_setup', 'parental_pin_unlock', 'parental_pin_lock'):
			from modules import dialogs
			if mode == 'parental_pin_setup': dialogs.parental_pin_setup()
			elif mode == 'parental_pin_unlock': dialogs.parental_pin_unlock()
			else: dialogs.parental_pin_lock()
		elif 'choice' in mode:
			from modules import dialogs
			if mode == 'page_jump_choice':
				dialogs.page_jump_choice(params)
			elif mode == 'scraper_color_choice':
				dialogs.scraper_color_choice(params['setting'])
			elif mode == 'scraper_dialog_color_choice':
				dialogs.scraper_dialog_color_choice(params['setting'])
			elif mode == 'scraper_quality_color_choice':
				dialogs.scraper_quality_color_choice(params['setting'])
			elif mode == 'imdb_images_choice':
				dialogs.imdb_images_choice(params['imdb_id'], params['rootname'])
			elif mode == 'set_quality_choice':
				dialogs.set_quality_choice(params['quality_setting'])
			elif mode == 'results_sorting_choice':
				dialogs.results_sorting_choice()
			elif mode == 'results_priority_quality_choice':
				dialogs.results_priority_quality_choice()
			elif mode == 'results_sort_priority_choice':
				dialogs.results_sort_priority_choice()
			elif mode == 'genre_sort_choice':
				dialogs.genre_sort_choice(params)
			elif mode == 'list_sort_choice':
				dialogs.list_sort_choice(params)
			elif mode == 'results_layout_choice':
				dialogs.results_layout_choice()
			elif mode == 'options_menu_choice':
				dialogs.options_menu(params)
			elif mode == 'play_trailer_choice':
				dialogs.play_trailer_choice(params)
			elif mode == 'meta_language_choice':
				dialogs.meta_language_choice()
			elif mode == 'image_language_choice':
				dialogs.image_language_choice()
			elif mode == 'certification_country_choice':
				dialogs.certification_country_choice()
			elif mode == 'parental_rating_choice':
				dialogs.parental_rating_choice()
			elif mode == 'extras_menu_choice':
				dialogs.extras_menu(params)
			elif mode == 'info_extra_choice':
				dialogs.info_extra_choice(params)
				# Quand cette action est appelée depuis un widget de skin, Kodi la traite
				# comme un GetDirectory et attend une fin de dossier après la fenêtre.
				# Sans cette fermeture propre, le clic "Parcourir" depuis la fenêtre
				# peut fonctionner côté addon mais échouer côté widget.
				try: end_directory(int(sys.argv[1]), False)
				except Exception as e: logger('info_extra_choice end directory skipped', str(e))
			elif mode == 'favourites_choice':
				dialogs.favourites_choice(params)
			elif mode == 'rating_choice':
				dialogs.rating_choice(params)
			elif mode == 'trakt_manager_choice':
				dialogs.trakt_manager_choice(params)
			elif mode == 'tmdb_manager_choice':
				dialogs.tmdb_manager_choice(params)
			elif mode == 'mdbl_manager_choice':
				dialogs.mdbl_manager_choice(params)
			elif mode == 'folder_scraper_manager_choice':
				dialogs.folder_scraper_manager_choice()
			elif mode == 'set_language_filter_choice':
				dialogs.set_language_filter_choice(params['filter_setting'])
			elif mode == 'extras_lists_choice':
				dialogs.extras_lists_choice()
			elif mode == 'random_choice':
				dialogs.random_choice(params['mode'], params)
		elif 'trakt.' in mode:
			if 'trakt_account_info' in mode:
				from menus.trakt import trakt_account_info
				trakt_account_info()
			elif 'hide_unhide_trakt_items' in mode:
				from menus.trakt_api import hide_unhide_trakt_items
				hide_unhide_trakt_items(params['action'], params['media_type'], params['media_id'], params['section'])
			else:
				from modules.utils import manual_function_import
				function = manual_function_import('indexers.trakt_api', mode.split('.')[-1])
				function(params)
		elif 'mdblist.' in mode:
			if 'mdbl_account_info' in mode:
				from menus.mdblist import mdbl_account_info
				mdbl_account_info()
		elif 'tmdb.' in mode:
			if 'edit_tmdb_list' in mode:
				from menus.tmdb import edit_tmdb_list
				edit_tmdb_list(params)
			elif 'update_tmdb_list' in mode:
				from menus.tmdb import update_tmdb_list
				update_tmdb_list(params)
			else:
				from modules.utils import manual_function_import
				function = manual_function_import('indexers.tmdb_api', mode.split('.')[-1])
				function(params)
		elif 'build' in mode:
			if 'build_trakt_list' in mode:
				from modules.utils import manual_function_import
				function = manual_function_import('menus.trakt', mode.split('.')[-1])
				function(params)
			elif 'build_mdb_list' in mode:
				from modules.utils import manual_function_import
				function = manual_function_import('menus.mdblist', mode.split('.')[-1])
				function(params)
			elif 'build_tmdb_list' in mode:
				from modules.utils import manual_function_import
				function = manual_function_import('menus.tmdb', mode.split('.')[-1])
				function(params)
			elif mode == 'build_movie_list':
				from menus.movies import Menu
				Menu(params).run()
			elif mode == 'build_tvshow_list':
				from menus.tvshows import Menu
				Menu(params).run()
			elif mode == 'build_season_list':
				from menus.seasons import Seasons
				Seasons(params).run()
			elif mode == 'build_episode_list':
				from menus.seasons import Seasons
				Seasons(params).run()
			elif mode == 'build_in_progress_episode':
				from menus.episodes import Menu
				Menu(params).run()
			elif mode == 'build_next_episode':
				from menus.episodes import Menu
				Menu(params).run()
			elif mode == 'build_my_calendar':
				from menus.episodes import Menu
				Menu(params).run()
			elif mode == 'build_my_anime_calendar':
				from menus.episodes import Menu
				Menu(params).run()
			elif mode == 'build_anime_calendar':
				from menus.episodes import Menu
				Menu(params).run()
			elif mode == 'build_navigate_to_page':
				from modules.dialogs import build_navigate_to_page
				build_navigate_to_page(params)
			elif mode == 'imdb_build_user_lists':
				from indexers.imdb_api import imdb_build_user_lists
				imdb_build_user_lists(params_get('media_type'))
			elif mode == 'build_popular_people':
				from menus.people import popular_people
				popular_people()
			elif mode == 'tmdb_build_keyword_results':
				from indexers.tmdb_api import tmdb_build_keyword_results
				tmdb_build_keyword_results(params['media_type'], params['query'])
		elif 'watched_unwatched' in mode:
			if mode == 'mark_as_watched_unwatched_episode':
				from caches.watched_cache import mark_as_watched_unwatched_episode
				mark_as_watched_unwatched_episode(params)
			elif mode == 'mark_as_watched_unwatched_season':
				from caches.watched_cache import mark_as_watched_unwatched_season
				mark_as_watched_unwatched_season(params)
			elif mode == 'mark_as_watched_unwatched_tvshow':
				from caches.watched_cache import mark_as_watched_unwatched_tvshow
				mark_as_watched_unwatched_tvshow(params)
			elif mode == 'mark_as_watched_unwatched_movie':
				from caches.watched_cache import mark_as_watched_unwatched_movie
				mark_as_watched_unwatched_movie(params)
			elif mode == 'watched_unwatched_erase_bookmark':
				from caches.watched_cache import erase_bookmark
				erase_bookmark(params_get('media_type'), params_get('tmdb_id'), params_get('season', ''), params_get('episode', ''), params_get('refresh', 'false'))
		elif 'toggle' in mode:
			if mode == 'toggle_provider':
				from modules.utils import toggle_provider
				toggle_provider()
			elif mode == 'toggle_language_invoker':
				from modules.kodi_utils import toggle_language_invoker
				toggle_language_invoker()
		elif 'history' in mode:
			if mode == 'search_history':
				from menus.history import search_history
				search_history(params)
			elif mode == 'clear_search_history':
				from menus.history import clear_search_history
				clear_search_history()
			elif mode == 'remove_from_history':
				from menus.history import remove_from_search_history
				remove_from_search_history(params)
			elif mode == 'discover_remove_from_history':
				from menus.discover import remove_from_history
				remove_from_history(params)
			elif mode == 'discover_remove_all_history':
				from menus.discover import remove_all_history
				remove_all_history(params)
		elif 'easynews.' in mode:
			from modules.utils import manual_function_import
			function = manual_function_import('menus.easynews', mode.split('.')[-1])
			function(params)
		elif 'alldebrid' in mode:
			from menus.alldebrid import Menu, resolve_ad
			if 'resolve_' in mode: resolve_ad(params)
			else: Menu().run(params)
		elif 'premiumize' in mode:
			notification('Premiumize n’est plus supporté par alkoFlix')
		elif 'real_debrid' in mode:
			from menus.real_debrid import Menu, resolve_rd
			if 'resolve_' in mode: resolve_rd(params)
			else: Menu().run(params)
		elif 'torbox' in mode:
			from menus.torbox import Menu, resolve_tb
			if 'resolve_' in mode: resolve_tb(params)
			else: Menu().run(params)
		elif 'offcloud' in mode:
			notification('Offcloud n’est plus supporté par alkoFlix')
		elif 'easydebrid' in mode:
			notification('EasyDebrid n’est plus supporté par alkoFlix')
		elif '_settings' in mode:
			if mode == 'open_settings':
				from modules.kodi_utils import open_settings
				open_settings(params_get('query'))
			elif mode == 'clean_settings':
				from modules.kodi_utils import clean_settings
				clean_settings()
			elif mode == 'clean_settings_window_properties':
				from modules.kodi_utils import clean_settings_window_properties
				clean_settings_window_properties()
		elif '_cache' in mode:
			from modules.cache import clear_all_cache, clear_cache, clear_internal_cache, clear_services_cache
			if mode == 'clear_all_cache': clear_all_cache()
			elif mode == 'clear_internal_cache': clear_internal_cache()
			elif mode == 'clear_services_cache': clear_services_cache()
			else: clear_cache(params_get('cache'))
		elif '_image' in mode:
			from menus.images import Images
			Images().run(params)
		elif '_text' in mode:
			from modules.kodi_utils import show_text
			show_text(params_get('heading'), params_get('text'), params_get('file'), params_get('font_size', 'small'), params_get('kodi_log', 'false') == 'true')
		elif '_view' in mode:
			if mode == 'choose_view':
				from modules.kodi_utils import choose_view
				choose_view(params['view_type'], params_get('content', ''))
			elif mode == 'set_view':
				from modules.kodi_utils import set_view
				set_view(params['view_type'])
			elif mode == 'clear_view':
				from modules.kodi_utils import clear_view
				clear_view(params['view_type'])
		##EXTRA modes##
		elif mode == 'get_search_term':
			from menus.history import get_search_term
			get_search_term(params)
		elif mode == 'tmdb_keyword_help':
			from menus.history import tmdb_keyword_help
			tmdb_keyword_help()
		elif mode == 'person_search':
			from menus.people import person_search
			person_search(params['query'])
		elif 'person_data_dialog' in mode:
			from menus.people import person_data_dialog
			person_data_dialog(params)
		elif mode == 'downloader':
			from modules.downloader import runner
			runner(params)
		elif mode == 'update_alkopaste_database':
			from magneto.alkopaste import sync_alkopaste_database_manual
			sync_alkopaste_database_manual()
		elif mode == 'clean_databases':
			from modules.cache import clean_databases
			clean_databases()
		elif mode == 'clean_thumbnails':
			from modules.thumbnails import thumb_cleaner
			thumb_cleaner()
		elif mode == 'clear_kodi_thumbnails':
			from modules.thumbnails import clear_kodi_thumbnail_cache
			clear_kodi_thumbnail_cache()
		elif mode == 'clear_kodi_temp':
			from modules.thumbnails import clear_kodi_temp_cache
			clear_kodi_temp_cache()
		elif mode == 'tmdbh_disable':
			from modules.tmdbh_control import set_tmdbh_enabled
			set_tmdbh_enabled(False)
		elif mode == 'tmdbh_enable':
			from modules.tmdbh_control import set_tmdbh_enabled
			set_tmdbh_enabled(True)
		elif mode == 'clear_tmdbh_cache':
			from modules.tmdbh_control import clear_tmdbh_cache
			clear_tmdbh_cache()
		elif mode == 'manual_add_nzb_to_cloud':
			from modules.debrid import Source
			Source(params).manual_add_nzb_to_cloud()
		elif mode == 'upload_logfile':
			from modules.kodi_utils import upload_logfile
			upload_logfile()
		elif mode == 'clear_source_manifest':
			from modules.kodi_utils import clear_source_manifest
			clear_source_manifest(params)
		elif mode == 'install_tmdbh_players':
			from modules.tmdbh_players import install_players
			install_players()
		elif mode == 'sync_existing_ratings':
			from modules.dialogs import sync_existing_ratings_choice
			sync_existing_ratings_choice()
		elif mode == 'sync_existing_favourites':
			from modules.dialogs import sync_existing_favourites_choice
			sync_existing_favourites_choice(params)
		elif mode == 'export_local_favourites':
			from modules.dialogs import export_local_favourites_choice
			export_local_favourites_choice(params)
		elif mode == 'delete_external_favourites':
			from modules.dialogs import delete_external_favourites_choice
			delete_external_favourites_choice(params)
		elif mode == 'sync_local_favourites':
			from modules.dialogs import sync_local_favourites_choice
			sync_local_favourites_choice()
		elif mode == 'restore_local_favourites':
			from modules.dialogs import restore_local_favourites_choice
			restore_local_favourites_choice()
		elif mode == 'myservices':
			from modules.myservices import authorize
			authorize()
		elif mode == 'backup_alkoflix_userdata':
			from modules.alkopastes_userdata_backup import backup_alkoflix_userdata
			backup_alkoflix_userdata()
		elif mode == 'restore_alkoflix_userdata':
			from modules.alkopastes_userdata_backup import restore_alkoflix_userdata
			restore_alkoflix_userdata()
		elif mode == 'edit_alkoflix_userdata_code':
			from modules.alkopastes_userdata_backup import edit_alkoflix_userdata_code
			edit_alkoflix_userdata_code()
		elif mode == 'set_alkoflix_userdata_role':
			from modules.alkopastes_userdata_backup import set_alkoflix_userdata_role
			set_alkoflix_userdata_role(params.get('role', ''))
		elif mode == 'reset_alkoflix_userdata_settings':
			from modules.alkopastes_userdata_backup import reset_alkoflix_userdata_settings
			reset_alkoflix_userdata_settings()
		elif 'refer_link' in mode:
			from modules.myservices import refer_link
			refer_link(params['query'])
		##alko modes###
		elif mode == 'speedTest':
			from alko.speedtest import magneto
			magneto()


if __name__ == '__main__':
	with Router() as r: r.routing(sys)

