# -*- encoding: utf-8 -*-
import manager
import runtime
import config
import theme
from widgets import widget
from widgets import canvas
from system import eloop
import audioplayerwin
import time
import os
from system.debug import trace, warning, error

class AlarmOutWin(audioplayerwin.AudioPlayerWin):
	"""
	알람이 울릴때의 default Window
	"""
	snooze_time = 5*60*1000
	#snooze_time = 10*1000#테스트
	increse_vol_limit_sec = 1*60

	def __init__(self, app, options, uid):
		self.__super.__init__(app, options, uid)
		self._opt_item = None
		self._avplayer.set_background(True)
		manager.timer.insert_activating_alarm(self)
		self.app.always_top = True
		self.increase_timer = None
		self.max_volume = 0
		self.snooze_timer = None
		runtime.events.connect('alarm.activated', self.new_alarm_active)
		self.add_callback('win-destroy', self.pre_win_destroy)

	def try_change_pm_fsm(self, pm_fsm):
		"""
		알람시 screensaver 진입하지 않게
		"""
		return False

	def pre_win_destroy(self):
		"""
		알람 종료시 event 받지 않음
		"""
		self.app.always_top = False
		runtime.events.disconnect('alarm.activated', self.new_alarm_active)
		manager.timer.remove_activating_alarm(self)

	def new_alarm_active(self):
		"""
		새로운 알람이 울리면 기존알람 종료
		"""
		self.close()
		warning('**'*10)
		warning('AlarmOutWin : new_alarm_active')

	def cb_snooze(self):
		"""
		snooze
		"""
		self.stop()
		self.stop_increase_timer()
		self.softbutton.set_dim('left', True)
		self.snooze_timer = eloop.Timer(self.snooze_time, self.active_alarm_by_snooze)

	def active_alarm_by_snooze(self):
		"""
		snooze 된 알람이 timer 에 의해 다시 울림
		"""
		self.stop()
		self.play()
		self.start_increase_timer()
		self.softbutton.set_dim('left', False)
		return False

	def start_increase_timer(self):
		"""
		시간이 지남에 따라 volume 증가
		"""
		def increase_vol():
			vol = self.get_volume()
			if vol >= self.max_volume:
				return False

			vol += 1
			self.set_volume(vol)
			return True

		if self.max_volume <= 1:
			return
		
		self.set_volume(1)
		timer_sec = self.increse_vol_limit_sec/(self.max_volume-1)
		self.increase_timer = eloop.Timer(timer_sec*1000, increase_vol)

	def stop_increase_timer(self):
		"""
		volume 이 최대값이면 timer 종료
		"""
		self.increase_timer = None

	def set_volume(self, vol):
		"""
		volume 설정
		"""
		self.submit_volume_level(vol)
		if self._vol_ctrl is not None:
			self._vol_ctrl.set_volume(vol)
	
	def get_volume(self):
		"""
		현재 volume 값
		"""
		grp = self._avplayer.get_audio_group()
		return manager.audio.volume.get_volume_level(grp)

	def error(self, *args):
		"""
		예외상황시 default buzz
		"""
		self.app.always_top = False
		manager.timer.activate_default_buzz(self.data)
		self.close()

	def create_softbutton(self):
		"""
		하단버튼 생성
		"""
		def on_clicked(desc):
			if desc == 'snooze':
				self.cb_snooze()
			elif desc == 'exit':
				self.stop()
				self.close()
		conf = {'left':(_('Snooze'), 'snooze'), 'right':(_('Exit'), 'exit')}
		self.softbutton = widget.SoftButtonContainer(self, conf)
		self.softbutton.add_callback('softbutton-clicked', on_clicked)

	def set_items(self, items):
		"""
		play item 을 설정
		"""
		self.__super.set_items(items)
		item = self.get_item()
		self.data = item['Infos']
		self.max_volume = self.data['volume']

	def new_avplayer(self):
		"""
		player 생성
		"""
		p = self.__super.new_avplayer()
		p.set_audio_group('alarmout')
		return p

	def reset_volume(self):
		"""
		volume 초기화
		"""
		vol = 1
		self.submit_volume_level(vol)
		if self._vol_ctrl is not None:
			self._vol_ctrl.set_volume(vol)
	
		self.start_increase_timer()

class AlarmOutPlayerWin(AlarmOutWin):
	"""
	기본 알람이 울릴때의 Window
	"""
	def __init__(self, app, options, uid):
		self.__super.__init__(app, options, uid)
		text_conf = {'align' : 'left center', 'font_size':18, 'pos':(15, 42-runtime.indicator_height)}
		self.station_txt = widget.SlideText(self, text_conf, runtime.app_width-30)
		self.station_txt.start_sliding()
		manager.system.set_amp(True)

	def set_items(self, items):
		"""
		alarm type 에 따라 item 설정
		"""
		self.__super.set_items(items)
		if self.data['type'] == 'Radio':
			self.station_txt.text = unicode(self.data['type_detail']['Radio Name'], 'iso8859_1').encode('utf-8')
		elif self.data['type'] == 'Weather':
			self.station_txt.text = runtime.db['settings.timezone_city']['name']
		elif self.data['type'] == 'Voice Alarm':
			self.station_txt.text = self.data['type']
		elif self.data['type'] == 'Favorite Broadcasts':
			self.station_txt.text = self.data['type_detail']['title']
		elif self.data['type'] == 'Horoscope':
			from widgets.extend import alarmutils
			txt = alarmutils.get_title_by_xml_key(alarmutils.get_birthday_horo_key())
			self.station_txt.text = txt
		else:
			self.station_txt.text = os.path.basename(self.data['type_detail'])
		#self.set_title(_(self.data['type']))
		self.set_title(_('Alarm'))


class AlarmOutDefaultPlayerWin(AlarmOutWin):
	"""
	default buzz 가 울릴때의 alarm player
	"""
	digit_imgs = [config.img_global_dir + 'common/number_d%d.png'%num for num in range(10)]
	icon_imgs = [config.img_global_dir + 'alarm/alarm_icon%s.png'% s for s in ('', '_1', '_2', '_3', '_dim')]
	def __init__(self, app, options, uid):
		self.__super.__init__(app, options, uid)
		self.draw_screen()
		self.draw_time_timer = None
		self.draw_icon_timer = None
		self.start_draw_time_timer()
		self.start_draw_icon_timer()
		manager.system.set_amp(True)

	def draw_screen(self):
		"""
		default layout
		"""
		height = 156-runtime.indicator_height
		_line = canvas.XGLine(self)
		_line.set_xy((50, height, 300, height))
		_line.color = theme.color.widget_line
		height = 57-runtime.indicator_height
		dcolon_img = canvas.XGImage(self, config.img_global_dir + 'common/number_dcolon.png', pos=(156, height))
		self.hour1_img =  canvas.XGImage(self, self.digit_imgs, pos=(46, height))
		self.hour2_img =  canvas.XGImage(self, self.digit_imgs, pos=(101, height))
		self.min1_img =  canvas.XGImage(self, self.digit_imgs, pos=(186, height))
		self.min2_img =  canvas.XGImage(self, self.digit_imgs, pos=(241, height))
		height = 181-runtime.indicator_height
		self.alarm_icon = canvas.XGImage(self, self.icon_imgs, pos=(50, height), align='left center')
		text_conf = {'align' : 'left center', 'font_size':18, 'pos':(99, height)}
		self.main_txt = canvas.XGText(self, text_conf)

	def set_items(self, items):
		"""
		item 설정
		"""
		self.__super.set_items(items)
		self.main_txt.text = _('Alarm') + ' %02d:%02d' % self.data['time']
		#self.set_title(_(self.data['type']))
		self.set_title(_('Alarm'))

	def start_draw_icon_timer(self):
		"""
		종 icon animation 시작
		"""
		def draw_icon():
			state = self.alarm_icon.get_state()
			state = (state+1)%4
			self.alarm_icon.set_state(state)
			return True
		self.alarm_icon.set_state(0)
		self.draw_icon_timer = eloop.Timer(300, draw_icon)

	def stop_draw_icon_timer(self):
		"""
		종 icon animation 종료
		"""
		self.draw_icon_timer = None
		self.alarm_icon.set_state(4)

	def start_draw_time_timer(self):
		"""
		시각 변경
		"""
		self.draw_time_timer = None
		curr_time = time.localtime()
		hour1 = curr_time[3] // 10
		hour2 = curr_time[3] % 10
		min1 = curr_time[4] // 10
		min2 = curr_time[4] % 10
		self.hour1_img.set_state(hour1)
		self.hour2_img.set_state(hour2)
		self.min1_img.set_state(min1)
		self.min2_img.set_state(min2)
		self.draw_time_timer = eloop.Timer((60-curr_time[5])*1000, self.start_draw_time_timer)
		return False

	def stop_draw_timer(self):
		"""
		시각 변경 종료
		"""
		self.draw_time_timer = None

	def cb_snooze(self):
		"""
		snooze
		"""
		self.stop_draw_icon_timer()
		self.__super.cb_snooze()

	def active_alarm_by_snooze(self):
		"""
		snooze 된 알람이 timer 에 의해 다시 울림
		"""
		self.start_draw_icon_timer()
		return self.__super.active_alarm_by_snooze()


class VoiceMemoOutPlayerWin(AlarmOutWin):
	"""
	음성메모 울릴때 Window
	"""
	play_controll_time_sec = 1*60
	def __init__(self, app, options, uid):
		self.__super.__init__(app, options, uid)
		self.play_controll_timer = None
		self.play_controll_cnt = 0
		self.start_play_controll_timer()
		self.pre_proc()
		self.set_title(_('Memos'))
		manager.system.set_amp(True)

	def pre_proc(self):
		"""
		Window 생성 준비
		"""
		x, y = self._play_bttn.pos
		self._play_bttn.pos = x, y+22
		self._deplay_bttn.pos = x, y+22

	def start_play_controll_timer(self):
		"""
		시나리오 주기에 맞게 play stop
		"""
		def play_controll():
			if self.play_controll_cnt == 0:
				self.stop()
			elif self.play_controll_cnt == 1:
				pass
			elif self.play_controll_cnt == 2:
				self.play()
			self.play_controll_cnt = (self.play_controll_cnt+1)%3
			return True
		self.play_controll_cnt = 0
		self.play_controll_timer = eloop.Timer(self.play_controll_time_sec*1000, play_controll)

	def stop_play_controll_timer(self):
		"""
		play control timer 종료
		"""
		self.play_controll_timer = None

	def cb_snooze(self):
		"""
		snooze
		"""
		self.stop_play_controll_timer()
		self.__super.cb_snooze()

	def active_alarm_by_snooze(self):
		"""
		snooze 된 알람이 timer 에 의해 다시 울림
		"""
		self.start_play_controll_timer()
		return self.__super.active_alarm_by_snooze()

	def set_items(self, items):
		"""
		item 설정
		"""
		self.__super.set_items(items)
		self.draw_screen()

	def draw_screen(self):
		"""
		layout
		"""
		imgs = [config.img_global_dir + 'common/list_bg%s.png'%str for str in ('', '_p', '')]
		img_border = (19,18,11,12)

		freq_bg = canvas.XGImage(self, imgs, border=img_border)
		freq_bg.pos = 66, 35-runtime.indicator_height
		freq_bg.size = 183, 28

		title_bg = canvas.XGImage(self, imgs, border=img_border)
		title_bg.pos = 66, 65-runtime.indicator_height
		title_bg.size = 243, 28

		time_bg = canvas.XGImage(self, imgs, border=img_border)
		time_bg.pos = 252, 35-runtime.indicator_height
		time_bg.size = 57, 28

		height = 49-runtime.indicator_height
		text_conf = {'align' : 'left center', 'font_size':14, 'pos':(74, height), 'color':theme.color.text}
		if self.data['duration'] == 'everyday':
			freq = _('Everyday')
		else:
			date_list = self.data['duration_detail']
			freq = '%02d/%02d/%04d' % (date_list[2], date_list[1], date_list[0])
		freq_main_txt = canvas.XGText(self, text_conf, text = freq)

		text_conf = {'align' : 'center center', 'font_size':14, 'pos':(280, height), 'color':theme.color.text}
		time_txt = canvas.XGText(self, text_conf, text = '%02d:%02d'%(self.data['time']))

		height = 79-runtime.indicator_height
		text_conf = {'align' : 'left center', 'font_size':16, 'pos':(74, height), 'color':theme.color.text}
		main_txt = canvas.XGText(self, text_conf, text = self.data['extend_data'])

		if self.data['type'] == 'voice':
			imgs = config.img_global_dir + 'memo/voice.png'
		else:
			self.draw_handwrite_image()
			imgs = config.img_global_dir + 'memo/handwriting.png'

		icon_image = canvas.XGImage(self, imgs)
		icon_image.pos = 28, 48-runtime.indicator_height

	def draw_handwrite_image(self):
		pass


class ImageMemoOutDefaultPlayerWin(VoiceMemoOutPlayerWin):
	"""
	image 가 있는 메모 울릴때 Window
	"""
	def draw_handwrite_image(self):
		"""
		draw image
		"""
		img = self.data['type_detail']
		if not img or not os.path.exists(img):
			img = config.img_global_dir + 'memo/add_image.png'

		main_img = canvas.XGImage(self, img)
		main_img.pos = 103, 98 -runtime.indicator_height
		main_img.size = 139, 104

	def pre_proc(self):
		pass


