from modules import kodi_utils
from modules.utils import manual_function_import
# from modules.kodi_utils import logger

location = kodi_utils.skin_location()
_active_dialogs = []

def _register_dialog(window):
	try:
		if window not in _active_dialogs: _active_dialogs.append(window)
	except: pass

def _unregister_dialog(window):
	try:
		if window in _active_dialogs: _active_dialogs.remove(window)
	except: pass

def close_custom_dialogs():
	# Ferme les fenêtres XML alkoFlix encore empilées avant une lecture plein écran.
	for window in reversed(list(_active_dialogs)):
		try: window.close()
		except: pass
	try: del _active_dialogs[:]
	except: pass

def strip_kodi_text_styles(label):
	label = str(label or '')
	for tag in ('[B]', '[/B]', '[I]', '[/I]'):
		label = label.replace(tag, '')
	return label

def open_window(import_info, skin_xml, **kwargs):
	'''
	import_info: tuple with ('module', 'function')
	'''
	try:
		xml_window = create_window(import_info, skin_xml, **kwargs)
		choice = xml_window.run()
		del xml_window
		return choice
	except Exception as exc:
		kodi_utils.logger('alkoFlix Windows', 'open_window failed: %s | xml=%s | import=%s' % (exc, skin_xml, import_info))
		return None

def create_window(import_info, skin_xml, **kwargs):
	'''
	import_info: tuple with ('module', 'function')
	'''
	try:
		function = manual_function_import(*import_info)
		xml_window = function(skin_xml, location, **kwargs)
		return xml_window
	except Exception as e:
		kodi_utils.logger('error in open_window', str(e))
		return kodi_utils.notification(32574)

def videoplayer(url, close_action=None, callback=None):
	def onAVStarted(self):
		self.playback_event = True
	Player = type('Player', (kodi_utils.xbmc_player,), {'onAVStarted': onAVStarted})
	player = Player()
	player.playback_event = False
	player.play(url)
	for i in range(50):
		kodi_utils.sleep(200)
		if player.playback_event: break
	if player.playback_event:
		if callable(close_action): close_action()
		close_custom_dialogs()
		kodi_utils.sleep(150)
		kodi_utils.execute_builtin('ActivateWindow(fullscreenvideo)')
	while player.isPlayingVideo(): kodi_utils.sleep(200)
	if player.playback_event and callable(callback): callback()

class BaseDialog(kodi_utils.window_xml_dialog):
	fanart = ''
	icon = kodi_utils.get_addoninfo('icon')
	def __init__(self, *args):
		kodi_utils.window_xml_dialog.__init__(self, args)
		self.closing_actions = kodi_utils.window_xml_closing_actions
		self.selection_actions = kodi_utils.window_xml_selection_actions
		self.context_actions = kodi_utils.window_xml_context_actions
		self.info_actions = kodi_utils.window_xml_info_action
		self.left_actions = kodi_utils.window_xml_left_action
		self.right_actions = kodi_utils.window_xml_right_action
		self.up_actions = kodi_utils.window_xml_up_action
		self.down_actions = kodi_utils.window_xml_down_action
		self.player = kodi_utils.player
		self.setProperty('alkoskins.icon', self.icon)
		_register_dialog(self)

	def close(self):
		# Fermeture défensive : certaines fenêtres XML Kodi peuvent déjà être détruites
		# quand on revient d'un menu contextuel, d'un DialogSelect ou d'un changement de fenêtre.
		# On évite alors de relancer des appels GUI sur une fenêtre morte.
		self._alkoflix_closed = True
		_unregister_dialog(self)
		try: return kodi_utils.window_xml_dialog.close(self)
		except: pass

	def is_closing(self):
		return getattr(self, '_alkoflix_closed', False)

	def clearProperties(self):
		try: return kodi_utils.window_xml_dialog.clearProperties(self)
		except: pass

	def safe_set_focus(self, window_id):
		if self.is_closing(): return
		try: self.setFocusId(window_id)
		except: pass

	def safe_get_listitem(self, window_id):
		if self.is_closing(): return None
		try: return self.get_listitem(window_id)
		except: return None

	def make_listitem(self):
		return kodi_utils.make_listitem()

	def build_url(self, params):
		return kodi_utils.build_url(params)

	def execute_code(self, command):
		return kodi_utils.execute_builtin(command)

	def get_position(self, window_id):
		return self.getControl(window_id).getSelectedPosition()

	def get_listitem(self, window_id):
		return self.getControl(window_id).getSelectedItem()

	def make_contextmenu_item(self, label, action, params):
		cm_item = self.make_listitem()
		cm_item.setProperty('alkoskins.context.label', strip_kodi_text_styles(label))
		cm_item.setProperty('alkoskins.context.action', action % self.build_url(params))
		return cm_item

	def get_infolabel(self, label):
		return kodi_utils.get_infolabel(label)

	def open_window(self, import_info, skin_xml, **kwargs):
		return open_window(import_info, skin_xml, **kwargs)

	def sleep(self, time):
		kodi_utils.sleep(time)

	def set_home_property(self, prop, value):
		kodi_utils.set_property('alkoflix_home_window.%s' % prop, value)

	def get_home_property(self, prop):
		return kodi_utils.get_property('alkoflix_home_window.%s' % prop)

