from Products.ZSQLCatalog.SQLCatalog import Query, SimpleQuery, ComplexQuery

portal = context.getPortalObject()
portal_catalog = portal.portal_catalog

try:
  if success: # full split ingestions successfully appendend
    # invalidate old ingestion objects
    data_stream = portal_catalog.getResultValue(
      portal_type = 'Data Stream',
      reference = reference,
      validation_state = "validated")
    if data_stream != None:
      data_ingestion = portal_catalog.getResultValue(
        portal_type = 'Data Ingestion',
        id = data_stream.getId())
      data_stream.setReference(data_stream.getReference() + "_invalid")
      data_stream.invalidate()
      if not data_ingestion.getReference().endswith("_invalid"):
        data_ingestion.setReference(data_ingestion.getReference() + "_invalid")
      data_an = portal_catalog.getResultValue(
        portal_type = 'Data Analysis',
        id = data_stream.getId())
      if data_an != None:
        data_an.setReference(data_an.getReference() + "_invalid")
      data_array = portal_catalog.getResultValue(
        portal_type = 'Data Array',
        id = data_stream.getId())
      if data_array != None:
        data_array.setReference(data_array.getReference() + "_invalid")
        data_array.invalidate()
  else: # split ingestion interrumped and restarted
    # invalidate draft datastreams and old started data ingestions
    for data_ingestion in portal_catalog(portal_type = "Data Ingestion",
                                         simulation_state = "started",
                                         reference = reference):
      if not data_ingestion.getReference().endswith("_invalid"):
        data_ingestion.setReference(data_ingestion.getReference() + "_invalid")
      data_ingestion.deliver()
    for data_stream in portal_catalog(portal_type = "Data Stream",
                                         validation_state = "draft",
                                         reference = reference):
      if not data_stream.getReference().endswith("_invalid"):
        data_stream.setReference(data_stream.getReference() + "_invalid")
except Exception as e:
  context.logEntry("ERROR in ERP5Site_invalidateSplitIngestions: " + str(e))
  pass
