import gtk
import gobject
from ptk.big_edit_box import *
import ptk.misc_widgets
import pynei18n
from pyneheaders import *

class UserConfigWin(gtk.Window):
	"""
	Allow the user to set his preferences like fonts, etc.
	"""
	def __init__(self, user, parent_win):
		gtk.Window.__init__(self)
		self.set_title(_("Pyne Preferences"))
		self.set_transient_for(parent_win)
		self.user = user

		box1 = gtk.VBox()
		self.add(box1)
		box1.show()

		self.notebook = gtk.Notebook()
		self.notebook.set_tab_pos(gtk.POS_TOP)
		box1.pack_start(self.notebook)
		self.notebook.show()

		# Add different config pages to notebook
		self.make_uiframe()
		self.make_miscframe()
		self.make_colframe()
		self.make_mimeframe()

		##########################
		buttonbox = ptk.misc_widgets.MyButtonBox()
		box1.pack_start(buttonbox, expand=False)
		buttonbox.show()

		button = gtk.Button(stock="gtk-ok")
		button.connect("clicked", self.set_prefs_end)
		buttonbox.pack_end(button)
		button.show()

		button = gtk.Button(stock="gtk-apply")
		button.connect("clicked", self.set_prefs)
		buttonbox.pack_end(button)
		button.show()

		button = gtk.Button(stock="gtk-cancel")
		button.connect("clicked", self.close)
		buttonbox.pack_end(button)
		button.show()

		self.show()

	def make_uiframe(self):
		"""
		User interface setup frame.
		"""
		frame = gtk.Frame(_("Interface"))
		frame.set_border_width(5)
		frame.show()

		box = gtk.VBox(spacing=5)
		box.set_border_width(5)
		frame.add(box)
		box.show()

		menu = gtk.Menu()
		menu.show()
		self.ui_style = self.user.ui_style
		
		combo = gtk.combo_box_new_text ()
		def _ch_uistyle (_widget):
			self.ui_style = combo.get_active ()
		
		for i in [ "Pyne default layout", "Classic layout", "Tabbed layout" ]:
			combo.append_text (i)
		box.pack_start (combo, expand=False)
		combo.set_active (self.user.ui_style)
		combo.connect ("changed", _ch_uistyle)
		combo.show ()
		
		label = gtk.Label(_("Disable quickview for:"))
		box.pack_start(label, expand=False)
		label.show()
		
		self.quickview_settings_box = big_edit_box( self.user,
		       (("opts", _("Newsreading"), VAR_TYPE_PACKED_BIT_BOOLEAN, 0, OPT_NO_QUICKVIEW_NNTP),
			("opts", _("Emails"), VAR_TYPE_PACKED_BIT_BOOLEAN, 0, OPT_NO_QUICKVIEW_MAIL))
		)
		box.pack_start(self.quickview_settings_box, expand=False)
		self.quickview_settings_box.show()

		label = gtk.Label(_("Interface"))
		self.notebook.append_page(frame, label)

	def make_miscframe(self):
		self.child_windows = []
		
		frame = gtk.Frame(_(" Misc "))
		frame.set_border_width(5)
		frame.show()

		miscbox = gtk.VBox()
		frame.add(miscbox)
		miscbox.show()

		bdfnt_box = gtk.HBox(spacing=5)
		bdfnt_box.set_border_width(5)
		miscbox.pack_start(bdfnt_box, expand=False)
		bdfnt_box.show()
		label = gtk.Label(_("Message body font:"))
		bdfnt_box.pack_start(label, expand=False)
		label.show()

		self.bodyfont_in = gtk.Entry()
		self.bodyfont_in.set_text(str(self.user.bodyfont))
		bdfnt_box.pack_start(self.bodyfont_in)
		self.bodyfont_in.show()

		button = gtk.Button(_(" Select "))
		button.connect("clicked", self.font_box)
		bdfnt_box.pack_start(button, expand=False)
		button.show()

		self.settings_box = big_edit_box( self.user,
		      ( ("html_parser", _("Parse html bodies with:"), VAR_TYPE_STRING, 0, 0),
		        ("edit_cmd", _("External editor"), VAR_TYPE_STRING, 0, 0),
			#("linewrap", _("Wrap lines at:"), VAR_TYPE_INTEGER, 0, 72),
		        ("replyhead", _("Reply header:"), VAR_TYPE_STRING, 0, 0),
			("opts", _("Double click to mark messages as read"), VAR_TYPE_PACKED_BIT_BOOLEAN, 0, OPT_2CLICK_MARK),
			("opts", _("Use external editor"), VAR_TYPE_PACKED_BIT_BOOLEAN, 0, OPT_EXT_EDITOR) )
		)
		miscbox.pack_start(self.settings_box, expand=False)
		self.settings_box.show()

		tabpos_box = gtk.HBox(spacing=5)
		miscbox.pack_start(tabpos_box, expand=False)
		tabpos_box.show()
		
		self.new_tabpos = self.user.tab_pos

		combo = gtk.combo_box_new_text ()
		def _ch_tabpos (_widget):
			self.new_tabpos = combo.get_active ()
		
		for i in [ _("Left"), _("Right"), _("Top"), _("Bottom") ]:
			combo.append_text (i)
		tabpos_box.pack_end (combo, expand=False)
		combo.set_active (self.user.tab_pos)
		combo.connect ("changed", _ch_tabpos)
		combo.show ()

		label = gtk.Label(_("Message view tab position:"))
		tabpos_box.pack_end(label, expand=False)
		label.show()
		
		label = gtk.Label(_("Messages"))
		self.notebook.append_page(frame, label)

	def make_colframe(self):
		"""
		Text colours page
		"""
		box = gtk.VBox()
		label = gtk.Label(_("Colours"))
		self.notebook.append_page(box, label)
		box.show()
		
		frame = gtk.Frame(_("Message text"))
		frame.set_border_width(5)
		box.pack_start(frame, expand=False)
		frame.show()

		box1 = gtk.VBox()
		box1.set_border_width(5)
		frame.add(box1)
		box1.show()

		table = gtk.Table(2, 3)
		table.set_row_spacings(5)
		table.set_col_spacings(5)
		box1.pack_start(table, expand=False)
		table.show()

		dictnames = ("col_header", "col_text", "col_quote")
		longnames = (_("Header text colour:"),
		             _("Body text colour:"),
			     _("Quoted text colour:"))
		for i in xrange(0, len(dictnames)):
			label = gtk.Label(longnames[i])
			label.set_justify(gtk.JUSTIFY_LEFT)
			table.attach(label, 0,1, i, i+1)
			label.show()
			
			colbutton = ptk.misc_widgets.ColorPickButton(_("Change"), self)
			colbutton.set_color(self.user.__dict__[dictnames[i]])
			table.attach(colbutton, 1,2, i,i+1)
			colbutton.show()
			self.__dict__[dictnames[i]] = colbutton

		frame = gtk.Frame(_("Message list"))
		frame.set_border_width(5)
		box.pack_start(frame, expand=False)
		frame.show()

		box1 = gtk.VBox()
		box1.set_border_width(5)
		frame.add(box1)
		box1.show()

		table = gtk.Table(2, 3)
		table.set_row_spacings(5)
		table.set_col_spacings(5)
		box1.pack_start(table, expand=False)
		table.show()

		dictnames = ("col_mnormal", "col_mnobody", "col_mmarked", "col_mreplied")
		longnames = (_("Normal message:"),
			     _("Without downloaded body:"),
			     _("Marked message:"),
			     _("Replied message:"))
		for i in xrange(0, len(dictnames)):
			label = gtk.Label(longnames[i])
			label.set_justify(gtk.JUSTIFY_LEFT)
			table.attach(label, 0,1, i, i+1)
			label.show()
			
			colbutton = ptk.misc_widgets.ColorPickButton(_("Change"), self)
			colbutton.set_color(self.user.__dict__[dictnames[i]])
			table.attach(colbutton, 1,2, i,i+1)
			colbutton.show()
			self.__dict__[dictnames[i]] = colbutton

	def make_mimeframe(self):
		"""
		Mime types page
		"""
		frame = gtk.Frame(_("MIME types"))
		frame.set_border_width(5)
		frame.show()
		label = gtk.Label(_("MIME types"))

		box = gtk.VBox()
		box.set_border_width(5)
		frame.add(box)
		box.show()

		cell = gtk.CellRendererText()
		self.mime_list = gtk.TreeView()

		col = gtk.TreeViewColumn(_("MIME type"), cell, text=0)
		col.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
		self.mime_list.append_column(col)
		col = gtk.TreeViewColumn(_("Handler"), cell, text=1)
		col.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
		self.mime_list.append_column(col)
		
		swin = gtk.ScrolledWindow()
		swin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
		swin.set_shadow_type(gtk.SHADOW_IN)
		box.pack_start(swin)
		swin.add(self.mime_list)
		swin.show()
		self.mime_list.show()
		
		# Make our own copy of the mime_types
		self.mime_types = []
		for m in self.user.mime_types:
			self.mime_types.append(list(m))
		
		self.update_mimelist()
		
		##########################
		buttonbox = ptk.misc_widgets.MyButtonBox()
		box.pack_start(buttonbox, expand=False)
		buttonbox.show()

		def add_mimetype(_w):
			mime = ["", "", 0]
			self.mime_types.append(mime)
			self.child_windows.append(EditMimeType(mime, self, new=1))
		
		def edit_mimetype(_w):
			iter = self.mime_list.get_selection().get_selected()
			if iter == None:
				return
			index = self.mime_list.get_model().get_value(iter[1], 2)
			# Edit the bastard
			self.child_windows.append(EditMimeType(self.mime_types[index], self))
			
		def delete_mimetype(_w):
			iter = self.mime_list.get_selection().get_selected()
			if iter == None:
				return
			index = self.mime_list.get_model().get_value(iter[1], 2)
			print index
			del self.mime_types[index]
			self.update_mimelist()

		def _on_click(widget, event):
			if event.type == gtk.gdk._2BUTTON_PRESS:
				edit_mimetype(widget)

		self.mime_list.connect("button_press_event", _on_click)

		button = gtk.Button("Add")
		button.connect("clicked", add_mimetype)
		buttonbox.pack_end(button)
		button.show()

		button = gtk.Button("Edit")
		button.connect("clicked", edit_mimetype)
		buttonbox.pack_end(button)
		button.show()

		button = gtk.Button("Delete")
		button.connect("clicked", delete_mimetype)
		buttonbox.pack_end(button)
		button.show()
		
		self.notebook.append_page(frame, label)

	def update_mimelist(self):
		list_store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_INT)
		self.selected_mimetype = None

		n = 0
		for mime in self.mime_types:
			iter = list_store.append()
			type, handler, use_internal = mime
			if use_internal == 1:
				handler = "Pyne internal"
			list_store.set(iter, 0, type, 1, handler, 2, n)
			n = n + 1
		self.mime_list.set_model(list_store)

	def font_box(self, _a=None):
		f = gtk.FontSelectionDialog(_("Message Body Font"))
		f.set_font_name(self.bodyfont_in.get_text())
		def _close(_button):
			f.destroy()
		def setfont(_button):
			self.bodyfont_in.set_text(f.get_font_name())
			f.destroy()
		f.show()
		f.ok_button.connect("clicked", setfont)
		f.cancel_button.connect("clicked", _close)

	def set_prefs(self, _a=None):
		"""
		Save the changed preferences.
		"""
		self.user.bodyfont = self.bodyfont_in.get_text()
		self.settings_box.apply_changes()
		self.quickview_settings_box.apply_changes ()

		self.user.col_text = self.col_text.get_color()
		self.user.col_header = self.col_header.get_color()
		self.user.col_quote = self.col_quote.get_color()

		self.user.col_mnormal = self.col_mnormal.get_color()
		self.user.col_mnobody = self.col_mnobody.get_color()
		self.user.col_mmarked = self.col_mmarked.get_color()
		self.user.col_mreplied = self.col_mreplied.get_color()

		self.user.tab_pos = self.new_tabpos
		self.user.ui_style = self.ui_style
		# update mainwins
		for i in self.user.windows.keys():
			self.user.windows[i].update_settings ()
		# Save changes
		self.user.save()

	def set_prefs_end(self, _a=None):
		"""
		Save changes and close.
		"""
		self.set_prefs()
		
		# Save mime types
		self.user.mime_types = []
		for mime in self.mime_types:
			self.user.mime_types.append(tuple(mime))

		self.close()

	def close(self, _a=None):
		# Close child windows
		while len(self.child_windows):
			self.child_windows[0].close()
		self.destroy()

class EditMimeType:
	def __init__(self, mimehandler, config_box, new=0):
		self.win = gtk.Window()
		self.win.set_title(_("Edit MIME type"))
		self.win.connect("delete_event", self.close)
		self.win.set_transient_for(config_box)
		self.mimehandler = mimehandler
		self.config_box = config_box
		self.new = new

		box = gtk.VBox()
		self.win.add(box)
		box.show()

		self.type = mimehandler[0]
		self.handler = mimehandler[1]
		self.use_pyne = mimehandler[2]

		self.edit_box = big_edit_box( self,
		      ( ("type", _("Mime type:"), VAR_TYPE_STRING, 0, 0),
		        ("handler", _("Handler program:"), VAR_TYPE_STRING, 0, 0),
		        ("use_pyne", _("Let pyne handle it"), VAR_TYPE_PACKED_BIT_BOOLEAN, 0, 1) )
		)

		box.pack_start(self.edit_box)
		self.edit_box.show()

		buttonbox = ptk.misc_widgets.MyButtonBox()
		box.pack_start(buttonbox, expand=False)
		buttonbox.show()

		button = gtk.Button(stock="gtk-ok")
		button.connect("clicked", self.save_changes)
		buttonbox.pack_end(button, expand=False)
		button.show()

		button = gtk.Button(stock="gtk-cancel")
		button.connect("clicked", self.close)
		buttonbox.pack_end(button, expand=False)
		button.show()

		self.win.show()

	def save_changes(self, _a=None):
		self.edit_box.apply_changes()
		self.mimehandler[0] = self.type
		self.mimehandler[1] = self.handler
		self.mimehandler[2] = self.use_pyne

		self.config_box.update_mimelist()
		self.config_box.child_windows.remove(self)
		self.win.destroy()

	def close(self, _a=None, _b=None):
		# First edit, and we cancelled so remove mimetype
		self.config_box.child_windows.remove(self)
		if self.new:
			try:
				self.config_box.mime_types.remove(self.mimehandler)
			except ValueError:
				pass
			self.config_box.update_mimelist()
		self.win.destroy()



syntax highlighted by Code2HTML, v. 0.9.1