#!/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 sys
import gtk
import pygtk
pygtk.require('2.0')
import thread
import traceback

from winswitch.consts import APPLICATION_NAME
from winswitch.server.server_monitor import set_show_info_cb, ServerMonitor
from winswitch.objects.session import Session
from winswitch.util.simple_logger import Logger
from winswitch.util.error_handling import display_error
from winswitch.ui.ui_util import get_ui_util
from winswitch.ui import icons



class InfoWindow(gtk.Window):
	def __init__(self):
		super(InfoWindow, self).__init__()
		self.connect("destroy", self.exit_app)
		self.connect("key-press-event", self.key_pressed)
		self.connect("button-release-event", self.button_released)
		Logger(self)
		self.log("init()")
		self.ui_util = get_ui_util()
		#window position/decorations/..
		#self.get_style().
		self.black = gtk.gdk.rgb_get_colormap().alloc_color('black')
		self.white = gtk.gdk.rgb_get_colormap().alloc_color('white')
		self.blue = gtk.gdk.rgb_get_colormap().alloc_color('blue')

		self.modify_bg( gtk.STATE_NORMAL, self.black )
		self.modify_fg( gtk.STATE_NORMAL, self.white )
		self.set_icon(icons.get("winswitch"))
		self.set_position(gtk.WIN_POS_CENTER)
		self.fullscreen()
		self.is_fullscreen = True

		#window contents:
		vbox = gtk.VBox(False, 0)
		self.add(vbox)
		image = gtk.Image()
		image.set_from_pixbuf(icons.get("winswitch_logo"))
		vbox.pack_start(image, True, True, 20)

		self.title_label = self.ui_util.make_label("Starting up... please wait", "sans 20")
		self.title_label.modify_fg( gtk.STATE_NORMAL, self.white )
		vbox.pack_start(self.title_label, True, True, 10)

		self.users_label = self.ui_util.make_label("", "sans 18")
		self.users_label.modify_fg( gtk.STATE_NORMAL, self.white )
		vbox.pack_start(self.users_label, True, True, 10)

		self.users_box = gtk.VBox()
		vbox.pack_start(self.users_box, True, True, 10)
		self.user_labels = []

		self.sessions_label = self.ui_util.make_label("", "sans 18")
		self.sessions_label.modify_fg( gtk.STATE_NORMAL, self.white )
		vbox.pack_start(self.sessions_label, True, True, 10)

		self.sessions_box = gtk.VBox()
		vbox.pack_start(self.sessions_box, True, True, 10)
		self.session_labels = []

		self.show_all()
		self.slog(None, "done")

	def exit_app(self, *args):
		self.slog(None, *args)
		gtk.main_quit()

	def key_pressed(self, widget, event):
		self.slog("keyval=%s" % event.keyval, widget, event)
		if event.keyval == 65307:
			gtk.main_quit()

		if self.is_fullscreen:
			self.unfullscreen()
		else:
			self.fullscreen()
		self.is_fullscreen = not self.is_fullscreen

	def button_released(self, *args):
		self.slog(None, *args)
		gtk.main_quit()

	def show_info_gui(self, server):
		self.slog(None, server)
		self.title_label.set_text(APPLICATION_NAME+" Server '%s'" % server.name)
		#Users
		users = server.get_active_users()
		if len(users)>0:
			self.users_label.set_text("%d users:" % len(users))
		else:
			self.users_label.set_text("No users")
		for label in self.user_labels:
			self.users_box.remove(label)
			del label
		self.user_labels = []
		for user in users:
			self.slog("added user '%s'" % user.name, server)
			txt = "%s on %s" % (user.name, user.host)
			label = self.ui_util.make_label(txt, "sans 15")
			label.modify_fg( gtk.STATE_NORMAL, self.blue )
			self.users_box.add(label)
			self.user_labels.append(label)
			label.show()
		#Sessions
		sessions = server.get_live_sessions(ignore=[])
		if len(sessions)>0:
			self.sessions_label.set_text("%d sessions:" % len(sessions))
		else:
			self.sessions_label.set_text("No sessions")
		for label in self.session_labels:
			self.sessions_box.remove(label)
			del label
		self.session_labels = []
		self.slog("sessions=%s" % sessions, server)
		self.slog("type(sessions)=%s" % type(sessions), server)
		for session in sessions:
			self.slog("added session '%s'" % session, server)
			txt = "%s" % session.name
			user = self.get_user(server.users, session.actor)
			if user and session.status == Session.STATUS_CONNECTED:
				txt += " used by %s" % user.name
			label = self.ui_util.make_label(txt, "sans 15")
			label.modify_fg( gtk.STATE_NORMAL, self.blue )
			self.sessions_box.add(label)
			self.session_labels.append(label)
			label.show()
		#print("GUI: Server: %s" % server.name)
		#print("GUI: Connected users: %s" % str(server.users))
		#print("GUI: Sessions: %s" % str(server.sessions))

	def get_user(self, users, uuid):
		if not uuid or not users or len(users)==0:
			return	None
		for user in users:
			if user.uuid == uuid:
				return	user
		return	None

def main():
	info_window = InfoWindow()
	try:
		import gobject
		server_monitor = ServerMonitor()
		def update_ui(server):
			gobject.idle_add(info_window.show_info_gui, server)
		set_show_info_cb(update_ui)
		thread.start_new_thread(server_monitor.start, ())
		gtk.main()
	except Exception, e:
		print("server_monitor.main() exception")
		traceback.print_exc(file=sys.stdout)
		display_error("ServerMonitor GUI failed to start", str(e))
	try:
		if server_monitor:
			server_monitor.stop()
	except:
		pass


if __name__ == "__main__":
	main()
