package org.flowable.engine.impl.util.condition;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import static org.springblade.flow.engine.custom.constants.BasicActivitiConstants.exActivitiPrefixURL;
import static org.springblade.flow.engine.custom.constants.BasicActivitiConstants.extensionAttributeName;

import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.engine.DynamicBpmnConstants;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.Condition;
import org.flowable.engine.impl.context.BpmnOverrideContext;
import org.flowable.engine.impl.context.Context;
import org.springblade.flow.engine.custom.handler.condition.NashornCondition;

/**
 * @author LoveMyOrange
 * @create 2022-02-05 23:07
 */
public class ConditionUtil {
    public static boolean hasTrueCondition(SequenceFlow sequenceFlow, DelegateExecution execution) {
        String conditionExpression = null;
        if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
            ObjectNode elementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(sequenceFlow.getId(), execution.getProcessDefinitionId());
            conditionExpression = getActiveValue(sequenceFlow.getConditionExpression(), DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION, elementProperties);
        } else {
            conditionExpression = sequenceFlow.getConditionExpression();
        }

        if (StringUtils.isNotEmpty(conditionExpression)) {
            String attributeValue = sequenceFlow.getAttributeValue(exActivitiPrefixURL,extensionAttributeName);
//            Expression expression = Context.getProcessEngineConfiguration().getExpressionManager().createExpression(conditionExpression);
            Condition condition = new NashornCondition(attributeValue);
            if (condition.evaluate(sequenceFlow.getId(), execution)) {
                return true;
            }

            return false;

        } else {
            return true;
        }

    }

    protected static String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) {
        String activeValue = originalValue;
        if (elementProperties != null) {
            JsonNode overrideValueNode = elementProperties.get(propertyName);
            if (overrideValueNode != null) {
                if (overrideValueNode.isNull()) {
                    activeValue = null;
                } else {
                    activeValue = overrideValueNode.asText();
                }
            }
        }
        return activeValue;
    }

}
