package com.flowable.local.work.service;

import com.flowable.dataobject.api.runtime.DataObjectInstanceVariableContainer;
import com.flowable.dataobject.api.runtime.DataObjectInstanceVariableContainerBuilder;
import com.flowable.dataobject.api.runtime.DataObjectRuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DataObjectUtils {

    protected final DataObjectRuntimeService dataObjectRuntimeService;

    public DataObjectUtils(DataObjectRuntimeService dataObjectRuntimeService) {
        this.dataObjectRuntimeService = dataObjectRuntimeService;
    }

    public void create(String tenantId, String definitionKey) {
        DataObjectInstanceVariableContainerBuilder dataObjectValueInstanceBuilder = dataObjectRuntimeService.createDataObjectValueInstanceBuilder();
        dataObjectValueInstanceBuilder.tenantId(tenantId);
        dataObjectValueInstanceBuilder.definitionKey(definitionKey);
        /*TODO: iterate list
        for (entry : list) {
            dataObjectValueInstanceBuilder.value(entry.key(), entry.value());
        }
         */
        dataObjectValueInstanceBuilder.create();
    }

    public void delete(String tenantId, String definitionKey) {
        List<DataObjectInstanceVariableContainer> dataObjects = dataObjectRuntimeService.createDataObjectInstanceQuery()
                .tenantId(tenantId)
                .definitionKey(definitionKey)
                .operation("searchAll")
                .list();
        for (DataObjectInstanceVariableContainer dataObjectInstanceVariableContainer : dataObjects) {
            dataObjectRuntimeService.deleteDataObject(dataObjectInstanceVariableContainer.getLookupId().toString(),
                    dataObjectInstanceVariableContainer.getDefinitionId());
        }
    }
}
