#!/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 gobject
import gtk

from winswitch.ui.ui_util import get_ui_util
from winswitch.ui import icons
from winswitch.util.config import modify_server_config

from winswitch.util.simple_logger import Logger
logger=Logger("config_servers", log_colour=Logger.CRIMSON)


def get_selected_server(list_view):
	selection = list_view.get_selection()
	(model, list_iter) = selection.get_selected()
	if not model or not list_iter:
		return	None
	name = list_view.get_model().get_value(list_iter, 0)
	for server in list_view.servers:
		if server.name == name:
			#self.debug("() found %s" % name)
			return	server
	#self.debug("() %s not found!" % name)
	return None

def view_clicked(list_view, event):
	if event.button == 2 or (event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS):
		server = get_selected_server(list_view)
		if server:
			list_view.edit_callback(server)

	elif event.button == 3:
		x = int(event.x)
		y = int(event.y)
		time = event.time
		pthinfo = list_view.get_path_at_pos(x, y)
		if pthinfo is not None:
			path, col, _, _ = pthinfo
			#get the currently selected server using path as get_selected_server(list_view) is set to the previous selection at this point!???
			try:
				server = list_view.servers[path[0]]
			except:
				server = None
			path, col, _, _ = pthinfo
			list_view.grab_focus()
			list_view.set_cursor(path, col, 0)
			menu = create_context_menu(server, list_view)
			menu.show_all()
			menu.popup( None, None, None, event.button, time)
			return 1

def toggle_enabled(list_view, server, new_state):
	server.enabled = new_state
	server.touch()
	modify_server_config(server, ["enabled"])
	populate_view(list_view, list_view.servers)
	if new_state is False and server.link:
		server.link.stop()

def create_context_menu(server, list_view):
	menu = gtk.Menu()
	menu.set_title("Server Settings")
	menu.append(get_ui_util().make_menuitem("Edit", "configure", None, list_view.edit_callback))
	if server:
		if server.enabled:
			menu.append(get_ui_util().make_menuitem("Disable", "unticked", None, lambda x : toggle_enabled(list_view, server, False)))
		else:
			menu.append(get_ui_util().make_menuitem("Enable", "ticked", None, lambda x : toggle_enabled(list_view, server, True)))
	menu.append(get_ui_util().make_menuitem("Delete", "minus", None, list_view.delete_callback))
	return	menu

def create_model():
	return	gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf)

def create_treeview(servers, edit_cb, delete_cb):
	view = gtk.TreeView(model = create_model())
	columns = ['Name', 'Address']
	index = 0
	for name in columns:
		cell = gtk.CellRendererText()
		column = gtk.TreeViewColumn(name, cell)
		column.add_attribute(cell, 'text', index)
		view.append_column(column)
		index += 1
	columns = ['Enabled', 'Connected', 'SSH']
	for name in columns:
		cell = gtk.CellRendererPixbuf()
		column = gtk.TreeViewColumn(name, cell)
		column.add_attribute(cell, 'pixbuf', index)
		view.append_column(column)
		index += 1
	#column_enabled.add_attribute(cell_name, 'background', 'gray')
	selection = view.get_selection()
	selection.set_mode(gtk.SELECTION_SINGLE)
	view.servers = servers
	view.server_changed_callbacks = {}
	view.edit_callback = edit_cb
	view.delete_callback = delete_cb
	view.connect("button_press_event", view_clicked)
	return	view

def populate_view(view, servers):
	logger.sdebug(None, view, servers)
	if not view or view.get_model() is None:
		return
	model = view.get_model()
	model.clear()
	ticked = icons.get("ticked_small")
	unticked = icons.get("unticked_small")
	view.servers = servers
	for server in servers:
		values = [server.name, "%s:%s" % (server.host, server.port)]
		for v in [server.enabled, server.is_connected(), server.ssh_tunnel]:
			if v:
				values.append(ticked)
			else:
				values.append(unticked)
		model.append(values)
		if server.ID not in view.server_changed_callbacks:
			view.server_changed_callbacks[server.ID] = server
			def server_changed_update_view():
				logger.sdebug()
				populate_view(view, servers)
				return view.get_model() is not None
			server.add_modified_callback(server_changed_update_view)

def clear_treeview(view, *args):
	logger.sdebug(None, view, *args)
	if not view or view.get_model() is None:
		return
	view.set_model(None)
