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

from winswitch.util.common import save_binary_file
from winswitch.util.simple_logger import Logger
from winswitch.globals import WIN32

SET_COOKIE = True							#use the NX cookie code for securing authentication
USE_OPTIONS_FILE = not WIN32				#doesn't work (cygwin paths?)
logger = Logger("nx_common", log_colour=Logger.CYAN)

def _get_options_string(options, display):
	opt = None
	for name,value in options.items():
		nv = "%s=%s" % (name, value)
		if not opt:
			opt = nv
		else:
			opt = "%s,%s" % (opt, nv)
	return	opt+display

def get_line_speed_str(line_speed):
	ls = int(line_speed)/1000
	if ls<100:
		return	"modem"
	if ls<1000:
		return	"isdn"
	ls = int(ls/1000)
	if ls<10:
		return	"wan"
	if ls<1000:
		return	"lan"
	return	"local"

BANDWIDTH_OPTIONS = ["modem", "isdn", "wan", "lan", "local"]

def nx_display_value(options, username, display, agent, optionsfile_dir):
	"""
	Returns the options as a string that can be used as a DISPLAY environment variable
	to be used by nxagent/nxproxy.
	If USE_OPTIONS_FILE is True (default), the options will be written to file
	and the path to that file will be returned with the correct nx syntax:
	(nx/nx,options=/path/to/file for nxagent)
	(options=/path/to/file for nxproxy)
	"""
	options_str = _get_options_string(options, display)
	if agent:
		prefix = "nx/nx,"
	else:
		prefix = ""
	if not USE_OPTIONS_FILE:
		return	prefix+options_str

	filename = os.path.join(optionsfile_dir, "nx_options.txt")
	save_binary_file(filename, options_str)
	logger.sdebug("saved options: '%s' to %s" % (options_str, filename), options, username, display, agent)
	return	prefix+"options=%s%s" % (filename, display)
