package com.germainsoftware.apm.analytics.audit;

dialect "mvel"
 
import com.germainsoftware.apm.data.*;
import com.germainsoftware.apm.data.model.*;
import com.germainsoftware.apm.storage.documentAudit.DocumentChange;
import java.time.*;

global org.slf4j.Logger logger;
global com.germainsoftware.apm.storage.documentAudit.DocumentAuditContext context;

/*rule "Document received"
when
  $update : DocumentChange( documentType == "Test-Document", path == "status" )
then
  logger.info("Value changed from '{}' to '{}' for {}", $update.oldValue, $update.value, $update.documentId);
end*/

rule "Status Change to Submitted"
when
  $update : DocumentChange( documentType == "Test-Document", path == "status", value == "Submitted" )
then
  logger.info("Value changed to submitted: {}", $update.documentId);

  var tx = new GenericTransaction();
  tx.name = $update.documentType;
  tx.type = "Test:Status Change";
  tx.timestamp = $update.timeCreated;
  tx.status = GenericTransaction.Status.IN_PROGRESS;
  tx.sequence = $update.documentId;
  context.storage.insertFact(tx);

  retract($update);
end

rule "Status Change from Submitted"
when
  $update : DocumentChange( documentType == "Test-Document", path == "status", oldValue == "Submitted" )
then
  logger.info("Value changed from submitted: {}", $update.documentId);

  var filter = String.format("type == 'Test:Status Change' && sequence == '%s'", $update.documentId);
  var res = context.highLevelQuery.find("GenericTransaction", filter);
  if (res.isEmpty()) {
    logger.warn("No previous status change found for: {}", $update.documentId);
    return;
  }

  var tx = (GenericTransaction)res.get(0);
  tx.status = GenericTransaction.Status.COMPLETED;
  tx.duration = DateTimeUtils.computeDuration(tx.timestamp, $update.timeCreated);
  tx.update = true;
  context.storage.updateFact(tx);

  retract($update);
end