#!/usr/bin/env python

import sys
import os.path

WSW_XDG_OPEN = os.path.abspath(__file__)

"""
This script is called by our libexec/winswitch/bin-override/xdg-open script
to open a file or URL either in a new session or directly on the client.
We pass the message to the server and let it do what is needed.
"""
def do_send_to_server(session_id, arg):
	from winswitch.util.file_io import get_local_server_socket
	from winswitch.net.commands import XDG_OPEN
	from winswitch.util.format_util import format_message
	from winswitch.net.unix_socket_util import unix_socket_send

	message = "%s\n" % format_message(XDG_OPEN, [session_id, arg])
	path = get_local_server_socket()
	unix_socket_send(path, message)

def send_to_server(session_id, arg):
	#print "send_to_server(%s,%s)" % (session_id, arg)
	try:
		do_send_to_server(session_id, arg)
		return 0
	except:
		import traceback
		traceback.print_exc()
		print("error sending command to server..")
		return 1

def main():
	if len(sys.argv)<3:
		print("invalid number of arguments")
		return	1
	session_id = sys.argv[1]
	arg = sys.argv[2]
	return send_to_server(session_id, arg)

if __name__ == "__main__":
	sys.exit(main())
