portal = context.getPortalObject()

compute_partition = context
remote_node = compute_partition.getParentValue()
assert remote_node.getPortalType() == 'Remote Node'

remote_project = remote_node.getDestinationProjectValue(portal_type='Project')
remote_person = remote_node.getDestinationSectionValue(portal_type='Person')

if compute_partition.getId() == 'SHARED_REMOTE':
  # Hardcoded ID behaviour
  local_instance_list = portal.portal_catalog(
    portal_type='Slave Instance',
    aggregate__uid=compute_partition.getUid()
  )

else:
  local_instance_list = [portal.portal_catalog.getResultValue(
    portal_type='Software Instance',
    aggregate__uid=compute_partition.getUid()
  )]

for local_instance in local_instance_list:
  # XXX TODO this will increase the workflow history
  # Use the 'cached' API instead
  remote_person.requestSoftwareInstance(
    project_reference=remote_project.getReference(),
    software_release=local_instance.getUrlString(),
    software_title='_remote_%s_%s' % (remote_node.getFollowUpReference(), local_instance.getReference()),
    software_type=local_instance.getSourceReference(),
    instance_xml=local_instance.getTextContent(),
    sla_xml=None,
    shared=(local_instance.getPortalType() == 'Slave Instance'),
    state={'start_requested': 'started', 'stop_requested': 'stopped'}[local_instance.getSlapState()]
  )
  requested_software_instance = context.REQUEST.get('request_instance')
  if requested_software_instance is not None:
    local_instance.setConnectionXml(requested_software_instance.getConnectionXml())
