package cn.axzo.workflow.core.engine.cmd;

import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.persistence.entity.PropertyEntity;
import org.flowable.common.engine.impl.persistence.entity.PropertyEntityImpl;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;

import java.util.Objects;

/**
 * 操作 ACT_GE_PROPERTY 表的写命令
 *
 * @author wangli
 * @since 2024-09-30 15:15
 */
public class CustomInsertPropertyCmd implements Command<Void> {
    private final String propertyName;
    private final String propertyValue;

    public CustomInsertPropertyCmd(String propertyName, String propertyValue) {
        this.propertyName = propertyName;
        this.propertyValue = propertyValue;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        PropertyEntity entity = processEngineConfiguration.getPropertyEntityManager().findById(propertyName);
        if (Objects.nonNull(entity)) {
            entity.setValue(propertyValue);
            processEngineConfiguration.getPropertyEntityManager().update(entity);
        } else {
            entity = new PropertyEntityImpl();
            entity.setName(propertyName);
            entity.setValue(propertyValue);
            processEngineConfiguration.getPropertyEntityManager().insert(entity);
        }
        return null;
    }
}
