import json
import random

portal = context.getPortalObject()

client_function = 'function/user'

password_length = 16
system_random = random.SystemRandom()
alphabet = string.ascii_letters + string.digits
client_init_password = ''.join(system_random.choice(alphabet) for i in range(password_length))

project = context.portal_catalog.getResultValue(
  portal_type='Project',
  # Do not test for title collision
  reference=project_reference,
  validation_state='validated'
)
if project:
  error_msg = "Client project %s already registered." % project_reference
  response_dict = dict(error_msg=error_msg)
  return json.dumps(response_dict)

user = context.portal_catalog.getResultValue(
  portal_type='Person',
  reference=client_username,
  validation_state='validated'
)
if user:
  error_msg = "Client account username not available: %s." % client_username
  response_dict = dict(error_msg=error_msg)
  return json.dumps(response_dict)

ors_reference = 'ors.' + ors_tag
# Search for DAU across all client projects to prevent tag collision
data_acquisition_unit = context.portal_catalog.getResultValue(
  portal_type='Data Acquisition Unit',
  reference=ors_reference,
  # Do not test for title collision
  validation_state='validated'
)
if data_acquisition_unit:
  error_msg = "ORS with tag %s already registered." % ors_tag
  response_dict = dict(error_msg=error_msg)
  return json.dumps(response_dict)

project = portal.project_module.newContent(
  portal_type='Project',
  reference=project_reference,
  title=project_title,
)
project.validate()
destination_project = project.getRelativeUrl()

user = portal.person_module.newContent(portal_type='Person', reference=client_username)
user.newContent(portal_type='Assignment', destination_project=destination_project, function=client_function).open()
user.newContent(portal_type='ERP5 Login', reference=client_username, password=client_init_password).validate()
user.validate()

data_acquisition_unit = portal.data_acquisition_unit_module.newContent(
  portal_type='Data Acquisition Unit',
  reference=ors_reference,
  title=ors_title
)
data_acquisition_unit.validate()
data_supply = data_acquisition_unit.DataAcquisitionUnit_createOrsDataSupply(destination_project, batch=1)

response_dict = dict(username=client_username, init_password=client_init_password)
return json.dumps(response_dict)
