#!/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 GSTVIDEO_TYPE
from winswitch.objects.session import Session
from winswitch.virt.client_util_base import ClientUtilBase
from winswitch.util.gstreamer_util import get_launch_wrapper_command_for_pipeline, get_hidden_wrapper_command, get_queue2_max_size_time_str
from winswitch.virt.options_common import GST_VIDEO_CODEC, GST_VIDEOSCALE_METHOD, FRAMERATE
from winswitch.util.gstreamer_util import THEORA, XVID, DIVX


class	GSTVideoClientBase(ClientUtilBase):

	def	__init__(self, update_session_status, notify_callback):
		ClientUtilBase.__init__(self, GSTVIDEO_TYPE, update_session_status, notify_callback)
		self.shadow_options_required = True				#show options before shadowing
		self.desktop_sizes = []

	def get_valid_video_codecs(self, server):
		codecs = [x for x in server.gstvideo_codecs if x in self.settings.gstvideo_codecs]
		BROKEN_CODECS = [THEORA, XVID, DIVX]		#these don't seem to work!?
		return [x for x in codecs if x not in BROKEN_CODECS]


	def do_real_attach(self, server, session, host, port):
		self.update_session_status(server, session, Session.STATUS_CONNECTING)
		pipeline = ["tcpclientsrc port=%s host=%s" % (port,host),
				"gdpdepay",
				"queue2 %s" % get_queue2_max_size_time_str(server.line_speed)
				]
		codec = session.options.get(GST_VIDEO_CODEC, None)
		if codec:
			pipeline.append("%sdec" % codec)
		pipeline += ["ffmpegcolorspace",
				self.settings.gstvideo_sink_plugin
				]
		window_icon = self.get_window_icon(session)
		cmd_args_list = get_hidden_wrapper_command(True, False)
		env = self.get_filtered_env(session)
		args = get_launch_wrapper_command_for_pipeline(cmd_args_list, False, None, session.name, pipeline, env, dock_icon=window_icon)
		self.exec_client(server, session, args, env=env, onstart_status=Session.STATUS_CONNECTED, onexit_status=Session.STATUS_AVAILABLE)

	def client_detach_session(self, server, client, session):
		"""
		Override so we can tell the server we have disconnected.
		(it should then shutdown the server end - since it cannot be re-used)
		"""
		ClientUtilBase.client_detach_session(self, server, client, session)
		self.update_session_status(server, session, Session.STATUS_AVAILABLE)

	def get_options_defaults(self):
		return	{
				GST_VIDEO_CODEC: "vp8",
				FRAMERATE: 5,
				GST_VIDEOSCALE_METHOD: 1,
				}
