#!/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

# Put this (executable) file in ~/.gnome2/nautilus-scripts/
# Then right click a directory or anywhere in current dir window
# to get the scripts->open-with-shared-tool menu option

import sys
import os

from winswitch.util.simple_logger import Logger, set_log_filename, set_log_dir
from winswitch.util.paths import CLIENT_DIR
set_log_dir(CLIENT_DIR)
set_log_filename("open_remotely.log")
logger=Logger("open_remotely", log_colour=Logger.HIGHLIGHTED_BLUE)

from winswitch.consts import APPLICATION_NAME
from winswitch.net.local_common import COMMAND_OPEN, make_local_client
from winswitch.net.local_common import CLIENT_SUCCESS, CLIENT_ERROR_CONNECTION_FAILED, CLIENT_ERROR_TIMEOUT, CLIENT_ERROR_NACK, CLIENT_ERROR_UNKNOWN_RESPONSE, CLIENT_UNKNOWN_ERROR
from winswitch.util.format_util import format_message


NAUTILUS_KEY="NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"


def error(title, msg=None):
	from winswitch.util.error_handling import display_error
	display_error(title, msg)
	sys.exit(1)

def main():
	selected_split = []
	selected=None
	if NAUTILUS_KEY in os.environ:
		selected=os.environ[NAUTILUS_KEY]
	logger.log("main() args=%s, nautilus files=%s" % (sys.argv, selected))
	if not selected:
		if len(sys.argv) <= 1:
			error("No files given", "You must specify the files to open.\nThis utility is only meant to be used by your file manager, is it installed correctly?")
		for arg in sys.argv[1:]:
			selected_split.append(arg.replace("\n","").replace("\r",""))
	else:
		sane_sel=selected.replace("\n","").replace("\r","")
		selected_split=sane_sel.split(" ")
	logger.log("main() selected files=%s" % selected_split)
	server_id = ""		#will use default...
	params = selected_split[:]
	params.insert(0, server_id)
	msg = format_message(COMMAND_OPEN, params)
	ret = None
	client = make_local_client()
	try:
		ret = client.send([msg])
		logger.log("main() exit code from send(%s)=%s" % (msg, ret))
	except Exception, e:
		error("error connecting to applet", str(e))

	if ret == CLIENT_SUCCESS:
		pass
	elif ret == CLIENT_ERROR_CONNECTION_FAILED:
		error("Failed to connect to the %s applet" % APPLICATION_NAME, "Is it running? Please try to start or re-start it..")
	elif ret == CLIENT_ERROR_TIMEOUT:
		error("Communication with the %s applet timed out" % APPLICATION_NAME, "This should not happen, sorry. You may try to re-start it...")
	elif ret == CLIENT_ERROR_NACK or ret == CLIENT_ERROR_UNKNOWN_RESPONSE:
		error("%s did not understand our request" % APPLICATION_NAME, "This should not happen, sorry. Maybe you have an old version running? If this problem persists, please try re-installing the latest version.")
	elif ret == CLIENT_UNKNOWN_ERROR:
		error("Failed to connect to the %s applet" % APPLICATION_NAME, "The system reported an internal error, more information may be available in the log files")


if __name__ == "__main__":
	main()
