#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import gtk

from winswitch.consts import AVATAR_ICON_SIZE, SPEED_NAMES
from winswitch.objects.global_settings import get_settings
from winswitch.util.simple_logger import Logger
from winswitch.util.common import csv_list
from winswitch.ui.config_common import new_config_window, table_init, make_button_hbox, add_tableline, add_table_sep
from winswitch.ui.ui_util import get_ui_util
from winswitch.ui import icons


user_info_windows = {}

def _get_user_info_key(user):
	return	user.uuid

def show_user_info_window(user, send_message=None):
	"""
	Show the UserPage for this user, creating it if necessary.
	"""
	key = _get_user_info_key(user)
	global user_info_windows
	user_info = user_info_windows.get(key)
	if not user_info:
		user_info = UserPage(user, send_message)
		user_info_windows[key] = user_info
	else:
		user_info.send_message = send_message
	user_info.unhide()

def close_all_user_info_windows():
	"""
	Closes all the SessionInfoWindows
	"""
	global user_info_windows
	for win in user_info_windows.values():
		win.close_window()



def create_user_form_box(form, send_message_callback=None):
	"""
	Returns a box with all the widgets needed to represent a user.
	A reference to all those widgets is added to "form".
	"""
	ui_util = get_ui_util()
	box = gtk.VBox(False, 0)
	# general config:
	table = table_init(form, columns=4)
	(_, form.avatar_image) = add_tableline(form, table, "Avatar", gtk.Image(), "This user's avatar", x_factor=2)
	(_, form.username) = add_tableline(form, table, "Username", gtk.Label(""), "This user's username", x_factor=2)
	(_, form.host) = add_tableline(form, table, "Host", gtk.Label(""), "This user's hostname", x_factor=2)
	(form.uuid_label, form.uuid) = add_tableline(form, table, "UUID", ui_util.make_label("", "courier 8", True), "This user's unique ID", x_factor=2)
	(form.locale_label, form.locale) = add_tableline(form, table, "Locale", gtk.Label(""), None, x_factor=2)
	add_table_sep(form, table, cols=4, preinc=1)
	(form.supports_xpra_label, form.supports_xpra_image) = add_tableline(form, table, "Supports Xpra", gtk.Image(), row_inc=False)
	(form.supports_nx_label, form.supports_nx_image) = add_tableline(form, table, "Supports NX", gtk.Image(), x_offset=2)
	(form.supports_vnc_label, form.supports_vnc_image) = add_tableline(form, table, "Supports VNC", gtk.Image(), row_inc=False)
	(form.supports_rdp_label, form.supports_rdp_image) = add_tableline(form, table, "Supports RDP", gtk.Image(), x_offset=2)
	(form.audio_codecs_label, form.audio_codecs) = add_tableline(form, table, "Audio Codecs", gtk.Label(""), row_inc=False)
	(form.video_codecs_label, form.video_codecs) = add_tableline(form, table, "Video Codecs", gtk.Label(""), x_offset=2)
	(form.line_speed_label, form.line_speed) = add_tableline(form, table, "Line Speed", gtk.Label(), x_factor=2)
	add_table_sep(form, table, cols=4, postinc=1)

	if send_message_callback:
		message_box = gtk.HBox(False, 0)
		form.message_entry = gtk.Entry(max=64)
		form.message_entry.connect("changed", lambda x : message_entry_changed(form))
		form.message_entry.connect("activate", lambda x : send_message_clicked(form, send_message_callback))
		message_box.pack_start(form.message_entry)
		form.send_message_button = ui_util.make_imagebutton("Send", "message", None,
							lambda x : send_message_clicked(form, send_message_callback), 16)
		form.send_message_button.hide()
		message_box.pack_start(form.send_message_button)
		add_tableline(form, table, "Send a message", message_box, "Send this user a short message", x_factor=2)
		message_entry_changed(form)	#just simulate to set the flag
	else:
		form.message_entry = None

	box.pack_start(table)
	return	box

def message_entry_changed(form):
	"""
	This fires whenever the message_entry widget is modified.
	We use this to enable the send button when there is a message to send.
	"""
	can_send = len(form.message_entry.get_text())>0
	form.send_message_button.set_sensitive(can_send)

def send_message_clicked(form, send_message_callback):
	"""
	The user clicked on send. Do it.
	"""
	message = form.message_entry.get_text()
	#self.log("(%s,%s) message=%s" % (form, send_message_callback, message))
	if len(message)>0 and send_message_callback:
		send_message_callback(message)
		form.message_entry.set_text("")



def populate_user_form(form, user):
	"""
	Populates a form create with create_user_form_box()
	The same "form" object must be passed in.
	"""
	empty_icon = icons.get("empty").scale_simple(16, 16, gtk.gdk.INTERP_HYPER)
	icon = None
	if user:
		icon = user.get_avatar_icon()
		if icon:
			icon = icon.scale_simple(AVATAR_ICON_SIZE, AVATAR_ICON_SIZE, gtk.gdk.INTERP_HYPER)
	else:
		icon = empty_icon
	form.avatar_image.set_from_pixbuf(icon)
	if user:
		form.username.set_text(user.username)
		form.host.set_text(user.host)
		form.uuid.set_text(user.uuid)
		form.locale.set_text(user.locale)
		form.supports_xpra_image.set_from_pixbuf(get_ui_util().true_false_icon(user.supports_xpra))
		form.supports_nx_image.set_from_pixbuf(get_ui_util().true_false_icon(user.supports_nx))
		form.supports_vnc_image.set_from_pixbuf(get_ui_util().true_false_icon(user.supports_vnc))
		form.supports_rdp_image.set_from_pixbuf(get_ui_util().true_false_icon(user.supports_rdp))
		form.audio_codecs.set_text(csv_list(user.gstaudio_codecs, before="", after=""))
		form.video_codecs.set_text(csv_list(user.gstvideo_codecs, before="", after=""))
		lsstr = str(user.line_speed)
		if user.line_speed in SPEED_NAMES:
			lsstr = SPEED_NAMES[user.line_speed]
	else:
		form.username.set_text("")
		form.host.set_text("")
		form.uuid.set_text("")
		form.locale.set_text("")
		form.supports_xpra_image.set_from_pixbuf(empty_icon)
		form.supports_nx_image.set_from_pixbuf(empty_icon)
		form.supports_vnc_image.set_from_pixbuf(empty_icon)
		form.supports_rdp_image.set_from_pixbuf(empty_icon)
		form.audio_codecs.set_text("")
		form.video_codecs.set_text("")
		lsstr = ""
	form.line_speed.set_text(lsstr)
	#advanced mode: show/hide some fields
	settings = get_settings()
	for w in [form.uuid_label, form.uuid, form.line_speed_label, form.line_speed]:
		if settings.advanced:
			w.show()
		else:
			w.hide()

	if form.message_entry:
		form.message_entry.set_text("")

class UserPage:

	def __init__(self, user, send_message):
		Logger(self, log_colour=Logger.YELLOW)
		self.user = user
		self.send_message = send_message
		self.ui_util = get_ui_util()
		self.window = self.create_window()
		self.populate_form()
		if self.message_entry:
			self.message_entry.grab_focus()

	def create_window(self):
		window = new_config_window("User: "+self.user.name)

		#Contents
		box = gtk.VBox(False, 10)
		box.set_spacing(15)
		# title
		box.pack_start(self.ui_util.make_label("User: "+self.user.name, "sans 16"))
		#contents
		box.pack_start(self.create_form_box())
		#buttons
		box.pack_start(make_button_hbox(("OK", gtk.STOCK_OK, self.close_window)))

		window.set_border_width(15)
		window.add(box)
		window.set_geometry_hints(box)
		self.ui_util.add_close_accel(window, self.close_window)
		window.connect('delete_event', self.close_window)
		return	window

	def create_form_box(self):
		return	create_user_form_box(self, self.send_message)

	def populate_form(self):
		populate_user_form(self, self.user)

	def close_window(self, *args):
		self.destroy_window()
		return True

	def destroy_window(self, *args):
		if self.window:
			self.window.destroy()
			self.window = None

	def unhide(self):
		if not self.window:
			self.window = self.create_window()
			self.populate_form()
		self.window.show_all()
		message_entry_changed(self)
		self.window.present()
