# Unity Mail, the Preferences Dialog
# Author: Dmitry Shachnev <mitya57@gmail.com>
# License: GNU GPL 3 or higher; http://www.gnu.org/licenses/gpl.html

from gi.repository import Gtk
from UnityMail import gettext, with_unity, with_messagingmenu
from UnityMail.config import ConfigFile, config_dir

_ = gettext.gettext

class TableLabel(Gtk.Label):
	def __init__(self, name = None):
		Gtk.Label.__init__(self, name)
		self.set_alignment(1, 0.5)

class PreferencesDialog(Gtk.Dialog):
	"""Unity Mail preferences dialog"""
	def __init__(self):
		self.init = False
		self.init_config()
		Gtk.Dialog.__init__(self, _('Unity Mail Preferences'), None, 0,
			(_('Apply'), Gtk.ResponseType.APPLY,
			_('Cancel'), Gtk.ResponseType.CANCEL))
		self.set_icon_name('preferences-system')
		self.connect('destroy', lambda w: Gtk.main_quit())
		self.set_position(Gtk.WindowPosition.CENTER)
		self.set_border_width(5)
		content_area = self.get_content_area()
		
		notebook = Gtk.Notebook()
		notebook.append_page(self.accounts_page(), Gtk.Label(_('Accounts')))
		notebook.append_page(self.urls_page(), Gtk.Label(_('URLs')))
		notebook.append_page(self.options_page(), Gtk.Label(_('Options')))
		content_area.add(notebook)
		
		self.datadicts = [{'Host': 'imap.gmail.com', 'Port': '993', 'Login': '', 'Passwd': ''}]
		self.show_all()
		self.init = True
		self.index = 0
	
	def init_config(self):
		config = ConfigFile(config_dir+'/unity-mail.conf')
		self.urls = {}
		for urlname in 'Home', 'Compose', 'Inbox', 'Sent':
			self.urls[urlname] = config.get_str_with_default(urlname, section = 'URLs')
		self.interval = config.get_int_with_default('Interval', 30)
		self.enable_notifications = config.get_bool_with_default('EnableNotifications', True)
		self.play_sound = config.get_bool_with_default('EnableSound', False)
		self.display_icons = config.get_bool_with_default('NotificationsHaveIcons', False)
		self.draw_attention = config.get_bool_with_default('DrawAttention', True)
		self.hide_count = config.get_bool_with_default('HideMessagesCount', False)
		self.command = config.get_str_with_default('ExecOnReceive')
		self.custom_sound = config.get_str_with_default('CustomSound')
	
	def accounts_page(self):
		acclabel = Gtk.Label()
		acclabel.set_markup('<b>'+_('Choose an account')+'</b>')
		self.sb = Gtk.SpinButton.new_with_range(1, 1, 1)
		self.sb.connect('changed', self.on_sb_changed)
		self.addbtn = Gtk.Button.new_with_label(_('Add'))
		self.addbtn.connect('clicked', self.add_dict)
		self.rmbtn = Gtk.Button.new_with_label(_('Remove'))
		self.rmbtn.connect('clicked', self.remove_dict)
		self.rmbtn.set_sensitive(False)
		accbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
		accbox.expand = True
		accbox.pack_start(self.sb, True, True, 0)
		accbox.pack_end(self.rmbtn, False, False, 0)
		accbox.pack_end(self.addbtn, False, False, 0)
		self.hostentry = Gtk.Entry()
		self.portentry = Gtk.Entry()
		self.loginentry = Gtk.Entry()
		self.passwdentry = Gtk.Entry()
		self.passwdentry.set_visibility(False)
		self.passwdentry.set_property('caps-lock-warning', True)
		srvlabel = Gtk.Label()
		srvlabel.set_markup('<b>'+_('Server data')+'</b>')
		infolabel = Gtk.Label()
		infolabel.set_markup('<b>'+_('Account data')+'</b>')
		table = Gtk.Table()
		table.attach(srvlabel, 0, 2, 0, 1)
		table.attach(Gtk.Label(_('Host:')), 0, 1, 1, 2, Gtk.AttachOptions.SHRINK)
		table.attach(Gtk.Label(_('Port:')), 0, 1, 2, 3, Gtk.AttachOptions.SHRINK)
		table.attach(self.hostentry, 1, 2, 1, 2)
		table.attach(self.portentry, 1, 2, 2, 3)
		table.attach(infolabel, 0, 2, 3, 4)
		table.attach(Gtk.Label(_('Login:')), 0, 1, 4, 5, Gtk.AttachOptions.SHRINK)
		table.attach(Gtk.Label(_('Password:')), 0, 1, 5, 6, Gtk.AttachOptions.SHRINK)
		table.attach(self.loginentry, 1, 2, 4, 5)
		table.attach(self.passwdentry, 1, 2, 5, 6)
		table.set_row_spacing(0, 5)
		table.set_row_spacing(2, 5)
		table.set_row_spacing(3, 5)
		table.set_col_spacings(8)
		
		page = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
		page.set_border_width(4)
		page.add(acclabel)
		page.add(accbox)
		page.add(table)
		return page
	
	def urls_page(self):
		self.homeentry = Gtk.Entry()
		self.homeentry.set_text(self.urls['Home'])
		self.composeentry = Gtk.Entry()
		self.composeentry.set_text(self.urls['Compose'])
		self.inboxentry = Gtk.Entry()
		self.inboxentry.set_text(self.urls['Inbox'])
		self.sententry = Gtk.Entry()
		self.sententry.set_text(self.urls['Sent'])
		table = Gtk.Table()
		table.set_col_spacings(8)
		table.attach(Gtk.Label(_('Home:')), 0, 1, 0, 1, Gtk.AttachOptions.SHRINK)
		table.attach(self.homeentry, 1, 2, 0, 1)
		table.attach(Gtk.Label(_('Compose:')), 0, 1, 1, 2, Gtk.AttachOptions.SHRINK)
		table.attach(self.composeentry, 1, 2, 1, 2)
		table.attach(Gtk.Label(_('Inbox:')), 0, 1, 2, 3, Gtk.AttachOptions.SHRINK)
		table.attach(self.inboxentry, 1, 2, 2, 3)
		table.attach(Gtk.Label(_('Sent:')), 0, 1, 3, 4, Gtk.AttachOptions.SHRINK)
		table.attach(self.sententry, 1, 2, 3, 4)
		page = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
		page.set_border_width(4)
		page.add(table)
		return page
	
	def options_page(self):
		self.intbox = Gtk.SpinButton.new_with_range(10, 300, 1)
		self.intbox.set_value(self.interval)
		self.notifyswitch = Gtk.Switch()
		self.notifyswitch.set_active(self.enable_notifications)
		self.sndswitch = Gtk.Switch()
		self.sndswitch.set_active(self.play_sound)
		self.sndswitch.connect('notify::active', self.on_sndswitch_activate)
		self.notifyiconswitch = Gtk.Switch()
		self.notifyiconswitch.set_active(self.display_icons)
		self.mmswitch = Gtk.Switch()
		self.mmswitch.set_active(self.draw_attention)
		self.hcswitch = Gtk.Switch()
		self.hcswitch.set_active(self.hide_count)
		self.commandchooser = Gtk.FileChooserButton()
		if self.command:
			self.commandchooser.set_filename(self.command)
		self.sndchooser = Gtk.FileChooserButton()
		if self.custom_sound:
			self.sndchooser.set_filename(self.custom_sound)
		table = Gtk.Table()
		table.set_col_spacings(8)
		table.attach(TableLabel(_('Refresh interval (seconds):')), 0, 1, 0, 1)
		table.attach(self.intbox, 1, 2, 0, 1, Gtk.AttachOptions.SHRINK)
		table.attach(TableLabel(_('Enable notifications:')), 0, 1, 1, 2)
		table.attach(self.notifyswitch, 1, 2, 1, 2, Gtk.AttachOptions.SHRINK)
		table.attach(TableLabel(_('Play sound on messages receive:')), 0, 1, 2, 3)
		table.attach(self.sndswitch, 1, 2, 2, 3, Gtk.AttachOptions.SHRINK)
		table.attach(TableLabel(_('Show icon in notifications:')), 0, 1, 3, 4)
		table.attach(self.notifyiconswitch, 1, 2, 3, 4, Gtk.AttachOptions.SHRINK)
		if with_messagingmenu:
			table.attach(TableLabel(_('Change color of messaging menu icon:')), 0, 1, 4, 5)
			table.attach(self.mmswitch, 1, 2, 4, 5, Gtk.AttachOptions.SHRINK)
		if with_unity:
			table.attach(TableLabel(_('Hide count when it is zero:')), 0, 1, 5, 6)
			table.attach(self.hcswitch, 1, 2, 5, 6, Gtk.AttachOptions.SHRINK)
		commandbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
		commandbox.add(Gtk.Label(_('Execute this command on messages receive:')))
		commandbox.pack_end(self.commandchooser, True, True, 0)
		if self.commandchooser.get_allocated_width() < 180:
			self.commandchooser.set_size_request(180, 0)
		self.sndbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
		self.sndbox.add(Gtk.Label(_('Custom sound to play:')))
		self.sndbox.pack_end(self.sndchooser, True, True, 0)
		if self.sndchooser.get_allocated_width() < 180:
			self.sndchooser.set_size_request(180, 0)
		self.sndbox.set_sensitive(self.play_sound)
		page = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)
		page.set_border_width(4)
		page.add(table)
		page.add(Gtk.Separator())
		page.add(commandbox)
		page.add(self.sndbox)
		return page
	
	def run(self):
		self.update_entries()
		Gtk.main()
	
	def save_all_settings(self):
		config = ConfigFile(config_dir+'/unity-mail.conf')
		for urlname, urlwidget in (('Home', self.homeentry),
		('Compose', self.composeentry), ('Inbox', self.inboxentry),
		('Sent', self.sententry)):
			config.save_with_default(urlname, urlwidget.get_text(), '', section='URLs')
		config.save_with_default('Interval', int(self.intbox.get_value()), 30)
		config.save_with_default('EnableNotifications', self.notifyswitch.get_active(), True)
		config.save_with_default('EnableSound', self.sndswitch.get_active(), False)
		config.save_with_default('NotificationsHaveIcons', self.notifyiconswitch.get_active(), False)
		config.save_with_default('DrawAttention', self.mmswitch.get_active(), True)
		config.save_with_default('HideMessagesCount', self.hcswitch.get_active(), False)
		config.save_with_default('ExecOnReceive', self.commandchooser.get_filename(), None)
		config.save_with_default('CustomSound', self.sndchooser.get_filename(), None)
		config.save_to_file(config_dir+'/unity-mail.conf')
	
	def add_dict(self, btn):
		self.update_datadicts()
		self.datadicts.append({'Host': 'imap.gmail.com', 'Port': '993', 'Login': '', 'Passwd': ''})
		self.sb.set_range(1, len(self.datadicts))
		self.sb.set_value(len(self.datadicts))
	
	def remove_dict(self, btn):
		self.update_datadicts()
		index = self.sb.get_value_as_int()-1
		del self.datadicts[index]
		self.init = False
		self.sb.set_range(1, len(self.datadicts))
		self.init = True
		self.update_entries()
		self.rmbtn.set_sensitive(len(self.datadicts)>1)
		if index+1 > len(self.datadicts):
			self.sb.set_value(index)
	
	def set_dicts(self, datadicts):
		self.init = False
		self.datadicts = datadicts
		self.index = 0
		self.sb.set_range(1, len(datadicts))
		self.update_entries()
		self.rmbtn.set_sensitive(len(self.datadicts)>1)
		self.init = True
	
	def on_sb_changed(self, sb):
		self.update_datadicts()
		self.index = self.sb.get_value_as_int()-1
		self.update_entries()
		self.rmbtn.set_sensitive(len(self.datadicts)>1)
	
	def on_sndswitch_activate(self, sndswitch, param):
		self.sndbox.set_sensitive(sndswitch.get_active())
	
	def update_entries(self):
		if self.datadicts:
			index = self.sb.get_value_as_int()-1
			self.hostentry.set_text(self.datadicts[index]['Host'])
			self.portentry.set_text(str(self.datadicts[index]['Port']))
			self.loginentry.set_text(self.datadicts[index]['Login'])
			self.passwdentry.set_text(self.datadicts[index]['Passwd'])
	
	def update_datadicts(self):
		if self.init:
			index = self.index
			self.datadicts[index]['Host'] = self.hostentry.get_text()
			if self.portentry.get_text():
				self.datadicts[index]['Port'] = self.portentry.get_text()
			else:
				self.datadicts[index]['Port'] = '993'
			self.datadicts[index]['Login'] = self.loginentry.get_text()
			self.datadicts[index]['Passwd'] = self.passwdentry.get_text()
