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

import time

from winswitch.consts import OSX_TYPE
from winswitch.globals import USERNAME
from winswitch.objects.session import Session
from winswitch.virt.server_util_base import ServerUtilBase
from winswitch.ui.icons import getraw


class	LocalOSXServerUtil(ServerUtilBase):
	"""
	Detects the local display and allows us to export it using VNC.
	"""

	def	__init__(self, config, add_session, remove_session, update_session_status, session_failed):
		ServerUtilBase.__init__(self, OSX_TYPE, 0, config, add_session, remove_session, update_session_status, session_failed)
		self.prelaunch_enabled = False
		self.screenshots_enabled = True
		self.default_session_name = "Main OS X Display"

	def get_config_options(self):
		return	self.get_config_options_base()+[
					"# enable screenshots of the desktop",
					"screenshots_enabled",
					"# name of the session shown for the Mac OS X desktop",
					"default_session_name"]
	def can_capture(self, session):
		""" always works on OSX? """
		return	self.screenshots_enabled

	def detect_existing_sessions(self, reloaded_sessions):
		#delete existing files:
		ServerUtilBase.zap_existing_sessions(self, reloaded_sessions)
		#detect local display if enabled:
		if self.config.export_local_displays:
			self.detect_local_displays()

	def detect_local_displays(self):
		self.sdebug()
		local_sessions = self.config.get_sessions_by_type(OSX_TYPE)
		if len(local_sessions)>0:
			return
		display_size = self.get_gdk_root_size()
		session = self.initialize_new_session(USERNAME, None, False, display_size, "Main", tcp_port=self.config.rdp_port)
		session.start_time = self.get_local_display_start_time()
		session.command = "Mac OS X Login"
		session.set_window_icon_data(getraw("osx"))
		session.name = self.default_session_name
		session.owner = self.get_local_display_owner()
		session.actor = session.owner
		session.full_desktop = True
		session.shared_desktop = False
		session.session_type = OSX_TYPE
		session.status = Session.STATUS_AVAILABLE
		session.can_clone_sound = False			#I don't think it can be done with gst plugins...
		session.can_export_sound = True			#with auto plugin
		session.can_import_sound = True			#with auto plugin
		session.gst_export_plugin = "autoaudiosrc"
		session.gst_export_plugin_options = {}
		session.gst_import_plugin = "autoaudiosink"
		session.gst_import_plugin_options = {}
		session.gst_clone_plugin = ""
		session.gst_clone_plugin_options = {}
		self.save_session(session)
		self.config.add_session(session)
		self.add_session(session)			#send the update session info to all clients
		self.sdebug("added OSX Display session %s" % (session.ID))
		return	True

	def get_local_display_start_time(self):
		#TODO
		return int(time.time())


	def get_local_display_owner(self):
		return	self.get_local_client_ID()


	def start_display(self, session, user, is_preload):
		self.serror("not supported!", session, user, is_preload)
		return False
	def stop_display(self, session, user, display):
		self.serror("not supported!", session, user, display)
	def start_session(self, user, server_command, screen_size, opts, filenames, success_callback=None, error_callback=None):
		self.serror("cannot start session!", user, server_command, screen_size, opts, filenames, success_callback, error_callback)

	def can_client_set_status(self, session, user_id, _from, _to):
		"""
		Let the clients tell us about some specific state transitions.
		On OSX we must let the client tell us, since I can't find a way to query the server.
		"""
		if not user_id or (user_id!=session.actor and user_id!=session.owner):		#double check: we shouldn't be here if not actor or owner
			return	False
		if session.actor and session.actor!=user_id:								#actor set and user_id is not the actor: dont allow
			return	False
		changeables = [Session.STATUS_CONNECTING, Session.STATUS_CONNECTED, Session.STATUS_AVAILABLE, Session.STATUS_IDLE]
		return _from in changeables and _to in changeables


	def get_test_port(self, session):
		return	self.config.rdp_port




def main():
	from winswitch.objects.server_settings import ServerSettings
	from winswitch.util.config import get_local_server_config
	from winswitch.util.simple_logger import Logger
	logger = Logger("localWindows_server_util")
	ss = get_local_server_config() or ServerSettings()
	def add_session(session):
		logger.sdebug("start_time=%s (%s seconds ago), command=%s" % (session.start_time, time.time()-session.start_time, session.command), session)
	lwin = LocalOSXServerUtil(ss, add_session, None, None, None)
	lwin.detect_local_displays()

if __name__ == "__main__":
	main()
