package com.customer.work.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.flowable.eventregistry.api.EventRegistry;
import org.flowable.eventregistry.api.model.EventPayloadTypes;
import org.flowable.eventregistry.api.runtime.EventPayloadInstance;
import org.flowable.eventregistry.impl.runtime.EventInstanceImpl;
import org.flowable.eventregistry.impl.runtime.EventPayloadInstanceImpl;
import org.flowable.eventregistry.model.EventPayload;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class TaskListenerService {
    private final EventRegistry eventRegistry;
    private final ObjectMapper objectMapper;

    public TaskListenerService(EventRegistry eventRegistry, ObjectMapper objectMapper) {
        this.eventRegistry = eventRegistry;
        this.objectMapper = objectMapper;
    }

    public void throwTaskListenerEvent(String rootCaseId, String eventKey, DelegateTask task, String message) {
        ObjectNode jsonTask = objectMapper.createObjectNode();
        jsonTask.put("modelId", task.getTaskDefinitionKey());
        jsonTask.put("assignee", task.getAssignee());
        jsonTask.put("name", task.getName());

        Collection<EventPayloadInstance> instances = new ArrayList<>();
        instances.add(new EventPayloadInstanceImpl(EventPayload.correlation("caseId", EventPayloadTypes.STRING), rootCaseId));
        instances.add(new EventPayloadInstanceImpl(new EventPayload("taskListenerTask", EventPayloadTypes.JSON), jsonTask));
        instances.add(new EventPayloadInstanceImpl(new EventPayload("taskListenerMessage", EventPayloadTypes.STRING), message));

        EventInstanceImpl event = new EventInstanceImpl(eventKey, instances, task.getTenantId());
        eventRegistry.sendSystemEventOutbound(event);
    }
}
