#coding=utf-8

from .pycawex import AudioUtilities
import wx
from globalPluginHandler import GlobalPlugin
import config
import gui

class GlobalPlugin(GlobalPlugin):
	def __init__(self, *args, **kwargs):
		super(GlobalPlugin, self).__init__(*args, **kwargs)
		try:
			self.IAEV = AudioUtilities.GetAudioEndpointVolume()
			self.conf = config.conf.get('volume_on_startup')
			if self.conf is None:
				self.conf = {}
				config.conf['volume_on_startup'] = self.conf
			self.conf['min_volume'] = int(self.conf.get('min_volume') if self.conf.get('min_volume') is not None else 1)
			self.conf['hear_volume'] = int(self.conf.get('hear_volume') if self.conf.get('hear_volume') is not None else 20)
			self.conf['unmute'] = True if self.conf.get('unmute') != 'False' else False
			
			self.check_volume()
			self.init_menu()
		except Exception as e:
			wx.CallAfter(wx.MessageBox, u'您可能無法使用「啟動音量」附加元件，建議從「 NVDA 功能表 -> 工具 -> 管理附加元件」移除「啟動音量」附加元件，或將此錯誤訊息貼到 www.nvda.org.tw\r\n錯誤訊息：' + str(e), '啟動音量異常', wx.ICON_ERROR)
		
	
	def terminate(self):
		gui.mainFrame.sysTrayIcon.toolsMenu.Remove(self.on_startup_menu.Id)
		self.on_startup_menu.Destroy()
		self.dlg.Destroy()
	
	def check_volume(self):
		conf = self.conf
		if conf.get('unmute'):
			self.IAEV.SetMute(False, None)
		if self.IAEV.GetMasterVolumeLevelScalar() * 100 < conf.get('min_volume'):
			self.IAEV.SetMasterVolumeLevelScalar(conf.get('hear_volume') /100.0, None)
		
	
	def init_menu(self):
		tools = gui.mainFrame.sysTrayIcon.toolsMenu
		self.on_startup_menu = tools.Append(wx.ID_ANY, u'啟動音量設定 (&S)')
		gui.mainFrame.sysTrayIcon.Bind(wx.EVT_MENU, self.on_on_startup_menu, self.on_startup_menu)
	
	def on_on_startup_menu(self, event):
		self.dlg = dlg = Dialog()
		self.read_from_config()
		gui.mainFrame.prePopup()
		if dlg.ShowModal() == wx.ID_OK:
			self.write_to_config()
		
		gui.mainFrame.postPopup()
	
	def read_from_config(self):
		conf, dlg = self.conf, self.dlg
		dlg.volume1_slider.SetValue(conf.get('min_volume'))
		dlg.volume2_slider.SetValue(conf.get('hear_volume'))
		dlg.unmute_chk.SetValue(conf.get('unmute'))
	
	def write_to_config(self):
		conf = self.conf
		dlg = self.dlg
		conf['min_volume'] = dlg.volume1_slider.GetValue()
		conf['hear_volume'] = dlg.volume2_slider.GetValue()
		conf['unmute'] = dlg.unmute_chk.IsChecked()
	

class Slider(wx.Slider):
	def __init__(self, *args, **kwargs):
		super(Slider, self).__init__(*args, **kwargs)
		self.SetPageSize(20)
		self.Bind(wx.EVT_KEY_DOWN, self.on_key_down)
	
	def on_key_down(self, event):
		key = event.GetKeyCode()
		if key == wx.WXK_UP:
			self.SetValue(self.GetValue() + self.GetLineSize())
		elif key == wx.WXK_DOWN:
			self.SetValue(self.GetValue() - self.GetLineSize())
		elif key == wx.WXK_PAGEUP:
			self.SetValue(self.GetValue() + self.GetPageSize())
		elif key == wx.WXK_PAGEDOWN:
			self.SetValue(self.GetValue() - self.GetPageSize())
		elif key == wx.WXK_HOME:
			self.SetValue(self.GetMax())
		elif key == wx.WXK_END:
			self.SetValue(self.GetMin())
		else:
			event.Skip()
		
	

class Dialog(wx.Dialog):
	def __init__(self):
		super(Dialog, self).__init__(parent=None, title='啟動音量')
		self.main_sizer = wx.BoxSizer(wx.VERTICAL)
		self.volume_sizer = wx.BoxSizer(wx.HORIZONTAL)
		self.main_sizer.Add(self.volume_sizer, flag=wx.EXPAND)
		self.volume1_label = wx.StaticText(self, label='當音量低於：')
		self.volume_sizer.Add(self.volume1_label)
		self.volume1_slider = Slider(self, value=1, style=wx.SL_VERTICAL | wx.SL_TICKS)
		self.volume_sizer.Add(self.volume1_slider, flag=wx.EXPAND)
		
		self.volume2_label = wx.StaticText(self, label='將音量調整為：')
		self.volume_sizer.Add(self.volume2_label)
		self.volume2_slider = Slider(self, value=20, style=wx.SL_VERTICAL | wx.SL_TICKS)
		self.volume_sizer.Add(self.volume2_slider, flag=wx.EXPAND)
		
		self.unmute_chk = wx.CheckBox(self, label='解除靜音 (&M)')
		self.unmute_chk.SetValue(wx.CHK_CHECKED)
		self.volume_sizer.Add(self.unmute_chk, 2, wx.ALL)
		
		self.buttons = self.CreateButtonSizer(wx.OK | wx.CANCEL)
		self.main_sizer.Add(self.buttons)
		
		self.SetSizerAndFit(self.main_sizer)
		self.volume1_slider.SetFocus()
	
