package com.flowable.local.work.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.flowable.cmmn.api.CmmnRuntimeService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;

@Component
public class VariableService {
    protected final ObjectMapper objectMapper;
    protected final CmmnRuntimeService cmmnRuntimeService;

    public VariableService(ObjectMapper objectMapper, CmmnRuntimeService cmmnRuntimeService) {
        this.objectMapper = objectMapper;
        this.objectMapper.registerModule(new JavaTimeModule());
        this.objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        this.cmmnRuntimeService = cmmnRuntimeService;
    }

    public JsonNode getVariable(@PathVariable String caseInstanceId, String variableName) {
        // Check parameters

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("caseInstanceId", caseInstanceId);
        map.put("variableName", variableName);
        map.put("value", this.cmmnRuntimeService.getVariables(caseInstanceId));
        return this.objectMapper.convertValue(map, JsonNode.class);
    }


}