package cn.stylefeng.workflow.instance.modular.manage.service.impl;

import cn.stylefeng.workflow.api.entity.instance.RuntimeInstance;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.api.pojo.InstanceVariable;
import cn.stylefeng.workflow.instance.api.InstanceVariableApi;
import cn.stylefeng.workflow.instance.modular.manage.service.RuntimeInstanceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class InstanceVariableImpl implements InstanceVariableApi {

    @Resource
    private RuntimeInstanceService runtimeInstanceService;

    @Override
    public InstanceVariable getInstanceVariableValue(Long instanceId) {
        LambdaQueryWrapper<RuntimeInstance> runtimeInstanceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        runtimeInstanceLambdaQueryWrapper.eq(RuntimeInstance::getInstanceId, instanceId);
        runtimeInstanceLambdaQueryWrapper.select(RuntimeInstance::getInstanceVariable);
        RuntimeInstance runtimeInstance = this.runtimeInstanceService.getOne(runtimeInstanceLambdaQueryWrapper);
        if (runtimeInstance == null) {
            return null;
        }
        return runtimeInstance.getInstanceVariable();
    }

    @Override
    public void updateVariableJson(InstanceContext instanceContext) {

        RuntimeInstance runtimeInstance = instanceContext.getRuntimeInstance();
        if (runtimeInstance == null) {
            return;
        }

        runtimeInstance.setInstanceVariable(instanceContext.getInstanceVariable());
        this.runtimeInstanceService.updateById(runtimeInstance);
    }

    @Override
    public void updateInstanceVariable(Long instanceId, InstanceVariable instanceVariable) {
        RuntimeInstance runtimeInstance = this.runtimeInstanceService.getById(instanceId);
        if (runtimeInstance == null) {
            return;
        }
        runtimeInstance.setInstanceVariable(instanceVariable);
        this.runtimeInstanceService.updateById(runtimeInstance);
    }

}