# -*- coding: utf-8 -*-
from windows.base_window import BaseDialog
from indexers.dialogs import person_menu_choice, extras_menu_choice, media_extra_info_choice
from modules.utils import adjust_premiered_date
from modules.metadata import episodes_meta
from modules import kodi_utils, settings
# from modules.kodi_utils import logger

class MediaInfo(BaseDialog):
	def __init__(self, *args, **kwargs):
		BaseDialog.__init__(self, *args)
		self.plot_id, self.cast_id = 50, 2000
		self.selected = None
		self.set_starting_constants(kwargs)
		self.set_properties()

	def onInit(self):
		self.make_cast()
		self.setFocusId(self.cast_id)
	
	def run(self):
		self.doModal()
		self.clearProperties()
		if self.selected:
			function, params = self.selected
			function(params)

	def onAction(self, action):
		if action in self.closing_actions: return self.close()
		focus_id = self.getFocusId()
		if focus_id == self.plot_id:
			if action in self.selection_actions: return self.show_plot()
			if self.show_shortcuts:
				if action == self.left_action: return media_extra_info_choice({'media_type': self.media_type, 'tmdb_id': self.tmdb_id})
				if action == self.right_action:
					self.selected = (extras_menu_choice, {'media_type': self.media_type, 'tmdb_id': self.tmdb_id})
					return self.close()
		elif focus_id == self.cast_id and action in self.selection_actions:
			try: chosen_var = self.get_listitem(focus_id).getProperty('name_lookup')
			except: return
			if not chosen_var: return
			self.selected = (person_menu_choice, {'key_id': chosen_var, 'reference_tmdb_id': self.tmdb_id})
			self.close()

	def set_infoline1(self):
		return '[B]  •  [/B]'.join([i for i in (self.year, self.rating, self.mpaa, self.get_duration(), self.stinger_dialog, self.status_infoline_value) if i])
	
	def make_status_infoline(self):
		status_str = self.status
		if self.media_type == 'tvshow' and self.status == 'Returning':
			try: next_aired_date = self.extra_info_get('next_episode_to_air')['air_date']
			except: next_aired_date = None
			if next_aired_date: status_str = '%s %s' % (self.status, adjust_premiered_date(next_aired_date, settings.date_offset())[0].strftime('%d %B %Y'))
		return status_str

	def make_stinger_dialog(self):
		stinger_dialog = ''
		if self.media_type == 'movie':
			stinger_keys = self.meta_get('stinger_keys', None)
			if not stinger_keys:
				try:
					keywords = self.meta_get('keywords', [])
					stinger_keys = [i['name'] for i in keywords['keywords'] if i['name'] in ('duringcreditsstinger', 'aftercreditsstinger')]
				except: pass
			if stinger_keys:
				stinger_names = tuple(sorted([{'duringcreditsstinger': 'During', 'aftercreditsstinger': 'After'}[i] for i in stinger_keys], reverse=True))
				stinger_dialog = {1: '%s Credits Stinger', 2: '%s & %s Credits Stinger'}[len(stinger_names)] % stinger_names
		return stinger_dialog

	def make_plot_and_tagline(self):
		self.plot = self.meta_get('tvshow_plot', '') or self.meta_get('plot', '') or ''
		if not self.plot: self.plot = '*** NO PLOT ***'
		self.tagline = self.meta_get('tagline') or ''
		if self.tagline: self.plot = '[I]%s[/I][CR][CR]%s' % (self.tagline, self.plot)

	def make_cast(self):
		def builder():
			for item in cast:
				try:
					listitem = kodi_utils.make_listitem()
					name = item['name']
					listitem.setProperty('name_lookup', name)
					listitem.setProperties({'thumbnail': item['thumbnail'] or empty_icon, 'display': '%s%s' % (name, ' as %s' % item['role'] if item['role'] else ''),
											'name_lookup': name})
					yield listitem
				except: pass
		try:
			empty_icon = kodi_utils.get_icon('empty_person')
			cast = self.meta.get('cast', [])
			if 'season' in self.meta: cast.extend([i for i in episodes_meta(self.meta_get('season'), self.meta) if i['episode'] == int(self.meta_get('episode'))][0]['guest_stars'])
			item_list = list(builder())
			self.setProperty('cast.number', 'x%s' % len(item_list))
			self.add_items(self.cast_id, item_list)
		except: pass

	def get_duration(self):
		time_str = ''
		if self.duration_data:
			hour, minute = divmod(self.duration_data, 60)
			if hour: time_str += '%dh' % hour
			if minute: time_str += '%s%sm' % (' ' if hour else '', '%d' % minute if minute < 10 else '%02d' % minute)
		return time_str

	def show_plot(self):
		return self.open_window(('windows.extras', 'ShowTextMedia'), 'textviewer_media.xml', text=self.plot, poster=self.poster)

	def set_starting_constants(self, kwargs):
		self.show_shortcuts = kwargs.get('show_shortcuts', False)
		self.media_type = kwargs.get('media_type')
		self.meta = kwargs.get('meta')
		self.meta_get = self.meta.get
		self.tmdb_id = self.meta_get('tmdb_id')
		self.extra_info = self.meta_get('extra_info')
		self.extra_info_get = self.extra_info.get
		self.title, self.year = self.meta_get('title'), str(self.meta_get('year'))
		self.poster = self.meta_get('poster') or kodi_utils.get_icon('box_office')
		self.fanart = self.meta_get('fanart') or kodi_utils.addon_fanart()
		self.clearlogo = self.meta_get('clearlogo') or ''
		self.rating = str(round(self.meta_get('rating'), 1)) if self.meta_get('rating') not in ('', '%', 0, 0.0, None) else None
		self.mpaa = self.meta_get('mpaa')
		self.status, self.duration_data = self.extra_info_get('status', '').replace(' Series', ''), int(float(self.meta_get('duration'))/60)
		self.status_infoline_value = self.make_status_infoline()
		self.stinger_dialog = self.make_stinger_dialog()
		self.make_plot_and_tagline()

	def set_properties(self):
		self.set_home_property('window_theme', self.get_home_property('window_theme'))
		self.setProperty('show_shortcuts', 'true' if self.show_shortcuts else 'false')
		self.setProperty('poster', self.poster)
		self.setProperty('fanart', self.fanart)
		self.setProperty('clearlogo', self.clearlogo)
		self.setProperty('line1', self.set_infoline1())
		self.setProperty('title', self.title)
		self.setProperty('plot', self.plot)
