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

"""Configuration centrale des XML des fenêtres d'information custom.

Ce module évite de dupliquer les noms de fichiers XML dans plusieurs
endroits du code. Les fenêtres legacy ont été retirées après validation
des XML séparés Films, Séries et Personnes.
"""

from threading import Thread
from modules.kodi_utils import logger

MOVIE_INFO_XML = 'extras_movie.xml'
TVSHOW_INFO_XML = 'extras_tvshow.xml'
COLLECTION_INFO_XML = 'extras_collection.xml'
PERSON_INFO_XML = 'extras_person.xml'


_MOVIE_TYPES = ('movie', 'movies', 'film', 'films')
_TVSHOW_TYPES = ('tvshow', 'tvshows', 'show', 'shows', 'tv', 'series', 'serie', 'season', 'seasons', 'episode', 'episodes')
_COLLECTION_TYPES = ('collection', 'collections', 'set', 'sets', 'saga', 'sagas')


def extras_window_xml(media_type):
	media_type = str(media_type or '').lower()
	if media_type in _MOVIE_TYPES: return MOVIE_INFO_XML
	if media_type in _TVSHOW_TYPES: return TVSHOW_INFO_XML
	if media_type in _COLLECTION_TYPES: return COLLECTION_INFO_XML
	log_info_window_event('XML', 'unknown media_type=%s -> %s' % (media_type, TVSHOW_INFO_XML))
	return TVSHOW_INFO_XML


def person_window_xml():
	return PERSON_INFO_XML


def log_info_window_event(section, message):
	try:
		logger('alkoFlix Info Windows', '%s -> %s' % (section, message))
	except Exception:
		pass


def log_info_window_error(section, action, exc):
	try:
		error = '%s: %s' % (type(exc).__name__, exc)
	except Exception:
		error = str(exc)
	log_info_window_event(section, '%s failed: %s' % (action, error))


def start_info_window_task(section, label, target, *args):
	# Lance les sections secondaires des fiches custom en arrière-plan,
	# avec un point de journalisation commun. Cela évite les démarrages
	# dupliqués/éparpillés dans chaque fenêtre.
	# Les exceptions GUI sont aussi interceptées si la fenêtre est fermée
	# pendant qu'un loader termine son travail.
	def runner():
		try:
			target(*args)
		except Exception as exc:
			log_info_window_error(section, 'loader %s' % label, exc)
	try:
		worker = Thread(target=runner)
		try: worker.daemon = True
		except Exception: pass
		worker.start()
		return worker
	except Exception as exc:
		log_info_window_error(section, 'start loader %s' % label, exc)
		return None
