#!/usr/bin/env python

from winswitch.ui import icons
from winswitch.consts import TYPE_SERVER, TYPE_LAPTOP, APPLICATION_NAME
from winswitch.util.simple_logger import Logger
#for talking to the applet
from winswitch.net.local_socket_client import get_responses, send_message
from winswitch.net.local_common import COMMAND_LIST_SERVERS, COMMAND_OPEN
from winswitch.util.format_util import parse_message_string, format_message

import nautilus				#@UnresolvedImport
import pygtk
pygtk.require("2.0")
import gtk
import time

WINSWITCH_LOGO = "winswitch_logo"
LAPTOP = "laptop_logo"
WORKSTATION = "workstation_logo"
SERVER = "server_logo"

DATA_TIMEOUT = 10


class NautilusWinSwitchMenuProvider(nautilus.MenuProvider):

	def __init__(self):
		Logger(self)
		self.debug()
		factory = gtk.IconFactory()
		factory.add(WINSWITCH_LOGO, gtk.IconSet(icons.get("winswitch_logo")))
		factory.add(LAPTOP, gtk.IconSet(icons.get("laptop")))
		factory.add(WORKSTATION, gtk.IconSet(icons.get("workstation")))
		factory.add(SERVER, gtk.IconSet(icons.get("server")))
		factory.add_default()
		self.servers = []
		self.last_query_time = 0

	def	get_servers(self):
		now = time.time()
		if now-self.last_query_time<DATA_TIMEOUT:
			self.sdebug("returning cached result")
			return	self.servers
		responses = get_responses([COMMAND_LIST_SERVERS])
		self.sdebug("responses=%s" % str(responses))
		servers = []
		if responses:
			for response in responses:
				(_, args) = parse_message_string(response)
				for server_spec in args:
					parts = server_spec.split(":")
					if len(parts)==3:
						servers.append(parts)
		self.last_query_time = time.time()
		self.servers = servers
		return	servers

	def close(self):
		pass

	def menu_activate_cb(self, menu, server_id, files):
		self.sdebug(None, menu, server_id, files)
		args = [server_id]
		for f in files:
			args.append(f)
		msg = format_message(COMMAND_OPEN, args)
		self.slog("message=%s" % msg, (menu, server_id, files))
		return_code = send_message(msg)
		self.sdebug("return_code=%s" % return_code, menu, server_id, files)
		#TODO: error handling here... alert user

	def get_file_items(self, window, files):
		try:
			from urllib import url2pathname
		except ImportError:
			from urllib.request import url2pathname		#@UnresolvedImport
		#can't handle non-local files (first basic check which doesn't walk directories; would be too long)
		local_files = []
		for i in range(len(files)):
			if files[i].get_uri_scheme() == 'file':
				#just keep the path name
				local_files.append(url2pathname(files[i].get_uri().replace("file://","")))
		if len(local_files) == 0:
			return
		servers = self.get_servers()
		self.debug("get_file_items(%s,%s) servers=%s" % (window, str(files), str(servers)))
		if not servers or len(servers)==0:
			return
		menus = []
		for name,server_type,server_id in servers:
			if server_type == TYPE_LAPTOP:
				icon_name = LAPTOP
			elif server_type == TYPE_SERVER:
				icon_name = SERVER
			else: # server_type == TYPE_WORKSTATION:
				icon_name = WORKSTATION
			menuitem = nautilus.MenuItem('NautilusSwitchMenuProvider::Open-on-%s' % server_id, 'Open on %s using %s' % (name, APPLICATION_NAME), '', icon_name)
			menuitem.connect('activate', self.menu_activate_cb, server_id, local_files)
			menus.append(menuitem)
		return menus

	def get_background_items(self, window, filename):
		return self.get_file_items(window, [filename])

	#we need to overload this method or the plugin won't even load
	def get_toolbar_items(self, window, filename):
		pass

	def __del__(self):
		print("Shutting down nautilus-clamscan extension")
