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

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

kw_dict = {"portal_type": "Data Set",
           "validation_state": "Invalidated"}

# data set
for data_set in portal_catalog(**kw_dict):
  if not data_set.getReference().endswith("_invalid"):
    context.logEntry("Invalidating data set and dependencies for: " + data_set.getReference())
    log("Ivalid Dataset: " + str(data_set.getReference()))
    reference_query = Query(**{'reference': data_set.getReference()+'/%'})
    kw_dict = {"portal_type": "Data Stream",
               "query": reference_query}
    for data_stream in portal_catalog(**kw_dict):
      if data_stream.getReference().startswith(data_set.getReference()+'/'):
        log("Related data stream: " + data_stream.getReference())
        portal.ERP5Site_invalidateIngestionObjects(data_stream.getReference())
    log("Invalidating data set")
    data_set.setReference(data_set.getReference() + "_invalid")

# data arrays
kw_dict = {"portal_type": "Data Array",
           "validation_state": "Invalidated"}

for data_array in portal_catalog(**kw_dict):
  if not data_array.getReference().endswith("_invalid"):
    log("Ivalid Data Array: " + str(data_array.getReference()))
    context.logEntry("Ivalid Data Array: " + str(data_array.getReference()))
    portal.ERP5Site_invalidateIngestionObjects(data_array.getReference())



# invalidate old (more than 10min) pending ingestions (split ingestions that were canceled/interrumped)
from DateTime import DateTime
now = DateTime()
now_minus_max = now - 1.0/24/60*9999
now_minus_10 = now - 1.0/24/60*10

catalog_kw = {'creation_date': {'query': (now_minus_max, now_minus_10), 'range': 'minmax'}, 'simulation_state': 'planned'}

for data_ingestion in portal_catalog(portal_type="Data Ingestion", **catalog_kw):
  # invalidate related Data Stream
  kw_dict = {"portal_type": "Data Stream",
             "reference": data_ingestion.getReference(),
             "validation_state": "Validated"}
  for data_stream in portal_catalog(**kw_dict):
    if not data_stream.getReference().endswith("_invalid"):
      log("%s %s (id:%s) invalidated" % (data_stream.getPortalType(), data_stream.getReference(), data_stream.getId()))
      data_stream.setReference(data_stream.getReference() + "_invalid")
      try:
        data_stream.invalidate()
      except:
        pass # fails if it's already invalidated
  data_ingestion.cancel()
  log("%s %s (id:%s) invalidated and canceled" % (data_ingestion.getPortalType(), data_ingestion.getReference(), data_ingestion.getId()))
  data_ingestion.setReference(data_ingestion.getReference() + "_invalid")
