# -*- coding: utf-8 -*-
import xbmcgui
import re
import json
from threading import Thread
from xml.dom.minidom import parse as mdParse
from modules import kodi_utils
from caches.settings_cache import get_setting, set_setting, restore_setting_default
from modules.utils import manual_function_import
# logger = kodi_utils.logger

def open_window(import_info, skin_xml, **kwargs):
	'''
	import_info: ('module', 'function')
	'''
	try:
		xml_window = create_window(import_info, skin_xml, **kwargs)
		choice = xml_window.run()
		del xml_window
		return choice
	except Exception as e:
		kodi_utils.logger('error in open_window', str(e))

def create_window(import_info, skin_xml, **kwargs):
	'''
	import_info: ('module', 'function')
	'''
	try:
		function = manual_function_import(*import_info)
		args = (skin_xml, kodi_utils.addon_path())
		xml_window = function(*args, **kwargs)
		return xml_window
	except Exception as e:
		kodi_utils.logger('error in create_window', str(e))
		return kodi_utils.notification('Error')

def window_manager(obj):
	def close():
		obj.close()
		kodi_utils.clear_property('gears.window_loaded')
		kodi_utils.clear_property('gears.window_stack')

	def monitor():
		timer = 0
		while not kodi_utils.get_property('gears.window_loaded') == 'true' and timer <= 5:
			kodi_utils.sleep(50)
			timer += 0.05
		kodi_utils.hide_busy_dialog()
		obj.close()
		kodi_utils.clear_property('gears.window_loaded')

	def runner(params):
		try:
			mode = params['mode']
			if mode == 'extras_menu_choice':
				from indexers.dialogs import extras_menu_choice
				extras_menu_choice(params)
			elif mode == 'person_data_dialog':
				from indexers.people import person_data_dialog
				person_data_dialog(params)
			else: close()
		except: close()

	def get_stack():
		try: window_stack = json.loads(kodi_utils.get_property('gears.window_stack'))
		except: window_stack = []
		return window_stack

	def add_to_stack(params):
		window_stack.append(params)
		kodi_utils.set_property('gears.window_stack', json.dumps(window_stack))

	def remove_from_stack():
		previous_params = window_stack.pop()
		kodi_utils.set_property('gears.window_stack', json.dumps(window_stack))
		return previous_params
	kodi_utils.show_busy_dialog()
	try:
		kodi_utils.clear_property('gears.window_loaded')
		current_params = obj.current_params
		new_params = obj.new_params
		window_stack = get_stack()
		if current_params: add_to_stack(current_params)
		if new_params:
			Thread(target=monitor).start()
			runner(new_params)
		elif window_stack:
			previous_params = remove_from_stack()
			if previous_params:
				Thread(target=monitor).start()
				runner(previous_params)
		else: close()
	except: close()
	kodi_utils.hide_busy_dialog()

def window_player(obj):
	def monitor():
		timer = 0
		while not kodi_utils.get_property('gears.window_loaded') == 'true' and timer <= 5:
			kodi_utils.sleep(50)
			timer += 0.05
		kodi_utils.hide_busy_dialog()
		obj.close()
		kodi_utils.clear_property('gears.window_loaded')

	def runner(params):
		try:
			mode = params['mode']
			if mode == 'extras_menu_choice':
				from indexers.dialogs import extras_menu_choice
				extras_menu_choice(params)
			else:
				from indexers.people import person_data_dialog
				person_data_dialog(params)
		except: close()
	try:
		window_player_url = obj.window_player_url
		if 'plugin.video.youtube' in window_player_url:
			if not kodi_utils.addon_installed('plugin.video.youtube') or not kodi_utils.addon_enabled('plugin.video.youtube'): return
		kodi_utils.clear_property('gears.window_loaded')
		current_params = obj.current_params
		player = kodi_utils.kodi_player()
		player.play(window_player_url)
		kodi_utils.sleep(2000)
		while not player.isPlayingVideo(): kodi_utils.sleep(100)
		obj.close()
		while player.isPlayingVideo(): kodi_utils.sleep(100)
		kodi_utils.show_busy_dialog()
		kodi_utils.sleep(1000)
		Thread(target=monitor).start()
		runner(current_params)
	except: obj.close()
	kodi_utils.hide_busy_dialog()

class BaseDialog(xbmcgui.WindowXMLDialog):
	def __init__(self, *args):
		xbmcgui.WindowXMLDialog.__init__(self, args)
		self.args = args
		self.player = kodi_utils.kodi_player()
		self.left_action = 1
		self.right_action = 2
		self.up_action = 3
		self.down_action = 4
		self.info_action = 11
		self.selection_actions = (7, 100)
		self.closing_actions = (9, 10, 13, 92)
		self.context_actions = (101, 108, 117)

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

	def get_setting(self, setting_id, setting_default=''):
		return get_setting(setting_id, setting_default)

	def set_setting(self, setting_id, value):
		set_setting(setting_id, value)

	def restore_setting_default(self, params):
		restore_setting_default(params)

	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, block=False):
		return kodi_utils.execute_builtin(command, block)
	
	def get_position(self, window_id):
		return self.get_control(window_id).getSelectedPosition()

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

	def add_items(self, _control, _items):
		self.get_control(_control).addItems(_items)

	def select_item(self, _control, _item):
		self.get_control(_control).selectItem(_item)

	def set_image(self, _control, _image):
		self.get_control(_control).setImage(_image)

	def set_label(self, _control, _label):
		self.get_control(_control).setLabel(_label)

	def set_text(self, _control, _text):
		self.get_control(_control).setText(_text)

	def set_percent(self, _control, _percent):
		self.get_control(_control).setPercent(_percent)

	def reset_window(self, _control):
		self.get_control(_control).reset()

	def get_control(self, control_id):
		return self.getControl(control_id)

	def make_contextmenu_item(self, label, action, params):
		cm_item = self.make_listitem()
		cm_item.set_properties({'label': label, 'action': action % self.build_url(params)})
		return cm_item

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

	def get_visibility(self, command):
		return kodi_utils.get_visibility(command)
	
	def open_window(self, import_info, skin_xml, **kwargs):
		return open_window(import_info, skin_xml, **kwargs)

	def run_addon(self, command, block=False):
		kodi_utils.run_plugin(command, block)

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

	def path_exists(self, path):
		return kodi_utils.path_exists(path)

	def translate_path(self, path):
		return kodi_utils.translate_path(path)

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

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

	def clear_home_property(self, prop):
		return kodi_utils.clear_property('gears.%s' % prop)

	def get_attribute(self, obj, attribute):
		return getattr(obj, attribute)

	def set_attribute(self, obj, attribute, value):
		return setattr(obj, attribute, value)

	def clear_modals(self):
		try: del self.player
		except: pass

	def notification(self, text, duration=3000):
		return kodi_utils.notification(text, duration)

	def addon_installed(self, addon_id):
		return kodi_utils.addon_installed(addon_id)

	def addon_enabled(self, addon_id):
		return kodi_utils.addon_enabled(addon_id)

class FontUtils:
	def execute_custom_fonts(self):
		change = self.skin_change_check()
		if not self.skin_change_check(): return
		replacement_values, skin_font_xml = [], ''
		replacement_values_append = replacement_values.append
		skin_folder = self.get_skin_folder()
		if skin_folder: skin_font_xml = kodi_utils.translate_path('special://skin/%s/Font.xml' % skin_folder)
		if skin_font_xml: self.skin_font_info = self.get_font_info(skin_font_xml) or self.default_font_info()
		else: self.skin_font_info = self.default_font_info()
		for item in ((21, False, 'font10'), (26, False, 'font12'), (30, False, 'font13'), (33, False, 'font14'), (38, False, 'font16'), (60, True, 'font60')):
			replacement_values_append(self.match_font(*item))
		skin_files = kodi_utils.list_dirs(kodi_utils.translate_path('special://home/addons/plugin.video.gears/resources/skins/Default/1080i/'))[1]
		for item in skin_files:
			self.replace_font(item, replacement_values)
		kodi_utils.set_property('gears.current_skin', self.current_skin)
		kodi_utils.set_property('gears.current_font', self.current_font)

	def get_skin_folder(self):
		folder_options = ('xml', '1080', '720', '1080p', '720p', '1080i', '720i', '16x9')
		skin_folder = None
		try:
			skin_folder = mdParse(kodi_utils.translate_path('special://skin/addon.xml')).getElementsByTagName('extension')[0].getElementsByTagName('res')[0].getAttribute('folder')
			if not skin_folder:
				s_folder = kodi_utils.list_dirs(kodi_utils.translate_path('special://skin'))[0]
				skin_folder = [i for i in s_folder if i in folder_options][0]
		except: pass
		return skin_folder

	def skin_change_check(self):
		self.current_skin, self.current_font = kodi_utils.current_skin(), kodi_utils.jsonrpc_get_system_setting('lookandfeel.font', 'Default')
		if self.current_skin != kodi_utils.get_property('gears.current_skin') or self.current_font != kodi_utils.get_property('gears.current_font'): return True
		return False

	def match_font(self, size, bold, fallback):
		font_tag = 'gears_%s%s' % (size, '_BOLD' if bold else '')
		size_range = range(int(size * 0.75), int(size * 1.25))
		compatibility_range = range(int(size * 0.50), int(size * 1.50))
		compatibility_fonts = [i['name'] for i in self.skin_font_info if i['name'] == fallback and i['size'] in compatibility_range]
		if compatibility_fonts: return (font_tag, compatibility_fonts[0])
		sized_fonts = [i for i in self.skin_font_info if i['size'] in size_range]
		if not sized_fonts: return fallback
		fonts = [i for i in sized_fonts if i['bold'] == bold and not i['extra_styles']] or [i for i in sized_fonts if i['bold'] == bold] \
				or [i for i in sized_fonts if not i['extra_styles']] or sized_fonts
		return (font_tag, [i['name'] for i in fonts if i['size'] == min([i['size'] for i in fonts], key=lambda k: abs(k-size))][0])

	def get_font_info(self, skin_font_xml):
		extras_keys = ('upper', 'uppercase', 'italic', 'capitalize', 'black', 'mono', 'symbol')
		results = []
		if not skin_font_xml: return results
		results_append = results.append
		try:
			all_fonts = mdParse(skin_font_xml).getElementsByTagName('fontset')
			try: fontset = [i for i in all_fonts if i.getAttribute('id').lower() == self.current_font.lower()][0]
			except: fontset = all_fonts[0]
			font_element = fontset.getElementsByTagName('font')
			for item in font_element:
				try: name = item.getElementsByTagName('name')[0].firstChild.data
				except: continue
				try: size = int(item.getElementsByTagName('size')[0].firstChild.data)
				except: continue
				try: style = item.getElementsByTagName('style')[0].firstChild.data.lower()
				except: style = ''
				name_compare = name.lower()
				bold = any('bold' in item for item in (name_compare, style))
				extra_styles = any(item in style for item in extras_keys)
				if not extra_styles: extra_styles = any(item in name_compare for item in extras_keys)
				results_append({'name': name, 'size': size, 'bold': bold, 'extra_styles': extra_styles})
		except: pass
		return results

	def replace_font(self, window, replacement_values):
		file = kodi_utils.translate_path('special://home/addons/plugin.video.gears/resources/skins/Default/1080i/' + window)
		with kodi_utils.open_file(file) as f: content = f.read()
		for item in replacement_values:
			try: content = re.sub(r'<font>(.*?)</font> <\!-- %s -->' % item[0], '<font>%s</font> <!-- %s -->' % (item[1], item[0]), content)
			except: pass
		with kodi_utils.open_file(file, 'w') as f: f.write(content)

	def default_font_info(self):
		return [{'name': 'font10', 'size': 21, 'bold': False, 'extra_styles': False},
				{'name': 'font12', 'size': 26, 'bold': False, 'extra_styles': False},
				{'name': 'font13', 'size': 30, 'bold': False, 'extra_styles': False},
				{'name': 'font14', 'size': 33, 'bold': False, 'extra_styles': False},
				{'name': 'font16', 'size': 38, 'bold': False, 'extra_styles': False},
				{'name': 'font45', 'size': 45, 'bold': False, 'extra_styles': False},
				{'name': 'font60', 'size': 60, 'bold': False, 'extra_styles': False}]
