from Products.ERP5Type.Log import log
from Products.ZSQLCatalog.SQLCatalog import Query, SimpleQuery, ComplexQuery

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

log("Invalidating related objects for reference " + reference)
context.logEntry("Invalidating objects for reference: " + reference)

portal_type_query = ComplexQuery(Query(portal_type='Data Stream'),
                                 Query(portal_type='Data Array'),
                                 Query(portal_type='Data Descriptor'),
                                 Query(portal_type='Data Ingestion'),
                                 operator="OR")
kw_dict = {"query": portal_type_query,
           "reference": reference}

for document in portal_catalog(**kw_dict):
  if not document.getReference().endswith("_invalid"):
    context.logEntry("%s %s (id:%s) invalidated" % (document.getPortalType(), document.getReference(), document.getId()))
    document.setReference(document.getReference() + "_invalid")
    try:
      document.invalidate()
    except:
      pass # fails if it's already invalidated or if it doens't allow invalidation (e.g. DI)
