import ldclient

def clientFactory(context):

	# to be changed in version 4
	server_base = None
	if context.getGlobalProperties().find("LDServer") is not None:
		server_base = context.getGlobalProperties().get("LDServer").getValue().getString()
	elif context.getGlobalProperties().find("Live Design Server") is not None:
		server_base = context.getGlobalProperties().get("Live Design Server").getValue().getString()
	elif context.getGlobalProperties().find("/discngine/ldconn/LiveDesignServerUrl") is not None:
		server_base = context.getGlobalProperties().get("/discngine/ldconn/LiveDesignServerUrl").getValue().getString()

	username = None
	if context.getGlobalProperties().find("LDUsername") is not None:
		username = context.getGlobalProperties().get("LDUsername").getValue().getString()
	elif context.getGlobalProperties().find("Live Design Username") is not None:
		username = context.getGlobalProperties().get("Live Design Username").getValue().getString()

	password = None
	if context.getGlobalProperties().find("LDPassword") is not None:
		password = context.getGlobalProperties().get("LDPassword").getValue().getString()
	elif context.getGlobalProperties().find("Live Design Password") is not None:
		password = context.getGlobalProperties().get("Live Design Password").getValue().getString()

	verifySSL = True
	if context.getGlobalProperties().find('/discngine/ldconn/VerifySSL') is not None:
		verifySSLConf = context.getGlobalProperties().get('/discngine/ldconn/VerifySSL').getValue().getString()
		if verifySSLConf is not None and verifySSLConf != 'True':
			verifySSL = False

	jsessionid = ''
	if context.getGlobalProperties().find('ldsession') is not None:
		jsessionid = context.getGlobalProperties().get('ldsession').getValue().getString()

	client = None
	if jsessionid != '' and jsessionid is not None and jsessionid != 'none':
		if server_base is not None and server_base != '' :
			client = ldclient.LDClient(server_base + '/livedesign/api', session_id=jsessionid, verify_ssl=verifySSL)
		else:
			raise Exception('Error using Pipeline Pilot gadget connection details : server name not found.')
	elif username is not None and username != '' and password is not None and password != '' and server_base is not None and server_base != '' :
		client = ldclient.LDClient(server_base + '/livedesign/api', username, password, verify_ssl=verifySSL)
	else:
		raise Exception('No username/password/server name found. On Pipeline Pilot, use the "Set LiveDesign Connection Details" component to specify these.')

	client.ping()

	return client

def getStringArrayValue(context, propertyName):
	propertyValue = []
	try :
		propertyValue = context.getGlobalProperties().get(propertyName).getValue().getStringArray()
	except Exception:
		propertyValue = context.getGlobalProperties().get(propertyName).getValue().getString().split("\n")
	if "" in propertyValue and len(propertyValue) == 1:
		propertyValue = []
	return propertyValue
