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


from winswitch.consts import SCREEN_TYPE
from winswitch.objects.session import Session
from winswitch.util.common import alphanumspace
from winswitch.util.ssh_util import get_tunnels_command
from winswitch.util.process_util import exec_nopipe
from winswitch.util.file_io import get_server_hostkey_filename
from winswitch.virt.client_util_base import ClientUtilBase


class	ScreenClientUtil(ClientUtilBase):

	def	__init__(self, update_session_status, notify_callback):
		ClientUtilBase.__init__(self, SCREEN_TYPE, update_session_status, notify_callback)

	def client_resume_session(self, server, session):
		self.slog(None, server, session)
		if session.display.startswith(":S-"):
			sess_id = "%s.%s" % (session.display[3:], session.name)
		else:
			sess_id = session.name
		cmd = "screen -d -r %s" % sess_id
		if not server.local:
			cmd = get_tunnels_command(self.settings.ssh_command, server, cmd, interactive=True, compression=True,
						host_key_file=get_server_hostkey_filename(self.server))
		xterm = self.settings.xterm_command
		if xterm.endswith("/xterm"):
			xterm_cmd = [xterm, "-T", alphanumspace(session.name), "-e", cmd]
		else:
			xterm_cmd = [xterm, "-e", cmd]
		process = exec_nopipe(xterm_cmd)
		session.actor = self.settings.uuid
		session.set_status(Session.STATUS_CONNECTED)
		session.touch()
		self.attached(server, session, process)
		session.actor = ""
		session.set_status(Session.STATUS_AVAILABLE)
		session.touch()
