from zExceptions import Unauthorized
if REQUEST is not None:
  pass #raise Unauthorized

if context.getSimulationState() not in ["draft", "planned"]:
  # Don't modify it anymore
  return

if subscription_condition_reference is not None:
  # It would be better use some clever API here.
  subscription_condition = context.portal_catalog.getResultValue(
    portal_type="Subscription Condition",
    reference=subscription_condition_reference,
    validation_state="validated")
else:
  subscription_condition = context.getSpecialiseValue()

if subscription_condition is None:
  raise ValueError(
    "It was not possible to find the appropriate Condition %s for this Subscription" \
      % subscription_condition_reference)

instance_xml = subscription_condition.SubscriptionCondition_renderParameter(
  amount=int(context.getQuantity()))
# Get Subscription condition for this Subscription Request
subscription_configuration = {
    "instance_xml": instance_xml,
    "software_type": subscription_condition.getSourceReference(),
    "url": subscription_condition.getUrlString(),
    "shared": subscription_condition.getRootSlave(),
    "sla_xml": subscription_condition.getSlaXml(),
}
email = context.getDestinationSectionValue().getDefaultEmailText()
now = DateTime()

context.edit(
  source_reference=subscription_configuration["software_type"],
  title="Subscription %s for %s" % (subscription_condition.getTitle(), email),
  url_string=subscription_configuration["url"],
  text_content=subscription_configuration["instance_xml"],
  start_date=now,
  root_slave=subscription_configuration["shared"],
  specialise_value=subscription_condition
)
