from DateTime import DateTime
from Products.ERP5Type.Log import log

# reference parameter example: supplier.dataset.filename.fif.EOF
# ingestion reference example: dataset_filename_fif

FALSE = "FALSE"
TRUE = "TRUE"

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

try:
  context.logEntry("Attempt to do a new ingestion with reference: %s" % reference)

  # remove supplier and eof from reference
  data_ingestion_reference = '/'.join(reference.split('/')[1:-1])
  EOF = reference.split('/')[-1]

  if data_ingestion_reference is "":
    context.logEntry("[ERROR] Data Ingestion reference is not well formated")
    raise ValueError("Data Ingestion reference is not well formated")

  data_ingestion = portal_catalog.getResultValue(
    portal_type = 'Data Ingestion',
    reference = data_ingestion_reference)

  if data_ingestion is None:
    return FALSE

  if data_ingestion.getSimulationState() == 'planned':
    try:
      if EOF != "EOF" and int(EOF) == 1:
        # The user has restarted a split ingestion that is already being processed
        return TRUE
    except:
      pass
    return FALSE

  context.logEntry("[ERROR] Data Ingestion reference %s already exists" % data_ingestion_reference)
  return TRUE
except Exception as e:
  context.logEntry("[ERROR] At script ingestionReferenceExists")
  context.logEntry("[ERROR] " + str(e))
  raise e
