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

portal_catalog = context.getPortalObject().portal_catalog

# search for dates older than one minute ago
old_start_date = addToDate(DateTime(), {'minute' : -1})
start_date_query = Query(**{'delivery.start_date': old_start_date, 'range': 'ngt'})
kw_dict = {"query": start_date_query,
           "portal_type": "Data Ingestion",
           "simulation_state": "started"}

parent_uid_list = [x.getUid() for x in portal_catalog(**kw_dict)]

if len(parent_uid_list) != 0:
  log("Stopping %s ingestions..." %(str(len(parent_uid_list))))
  context.logEntry("[Called by alarm] Stopping %s ingestions" %(str(len(parent_uid_list))))
  kw_dict = {"portal_type": "Data Ingestion Line",
             "resource_portal_type": "Data Product",
             "parent_uid": parent_uid_list}

  parent_uid_list = [x.getUid() for x in portal_catalog(**kw_dict)]

  for data_ingestion_line in portal_catalog(**kw_dict):
    data_ingestion = data_ingestion_line.getParentValue()
    resource = data_ingestion_line.getResourceValue()
    log("data_ingestion: " + str(data_ingestion.getReference()))
    log("resource: " + str(resource.getReference()))
    if "big_data/ingestion/batch_ingestion" in resource.getUseList():
      data_ingestion.setStopDate(DateTime())
      data_ingestion.stop()
      log("DATA INGESTION STOPPED")
      context.logEntry("Data Ingestion '%s' stopped." % data_ingestion.getId())
    else:
      raise ValueError("resource.getUseList must be 'big_data/ingestion/batch_ingestion'")
