package cn.axzo.workflow.starter.mq.broadcast.consumer;

import cn.axzo.framework.rocketmq.Event;
import cn.axzo.framework.rocketmq.EventConsumer;
import cn.axzo.framework.rocketmq.EventHandler;
import cn.axzo.workflow.starter.WorkflowEngineStarterProperties;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 流程引擎服务广播的事件监听器
 *
 * @author wangli
 * @since 2024/5/21 15:50
 */
public class WorkflowEngineBroadcastEventListener implements EventHandler, InitializingBean {
    private final Logger log = LoggerFactory.getLogger(WorkflowEngineBroadcastEventListener.class);
    private final EventConsumer eventConsumer;
    private final WorkflowEngineStarterProperties starterProperties;
    private final List<WorkflowListener> workflowListeners;

    public WorkflowEngineBroadcastEventListener(EventConsumer eventConsumer, WorkflowEngineStarterProperties workflowEngineStarterProperties, List<WorkflowListener> workflowListeners) {
        this.eventConsumer = eventConsumer;
        this.starterProperties = workflowEngineStarterProperties;
        this.workflowListeners = workflowListeners;
    }

    @Override
    public void onEvent(Event event, EventConsumer.Context context) {
        if (Objects.isNull(event) || Objects.isNull(event.getEventCode())) {
            log.warn("illegal event code: {}", event);
            return;
        }

        try {
            JSON.parse(JSON.toJSONString(event.getData()));
        } catch (Exception e) {
            log.warn("event data json format error, will be ignored, messageId: {}", context.getMsgId());
            return;
        }

        if (CollectionUtils.isEmpty(workflowListeners)) {
            log.warn("no business listeners implementation found, please check @Component annotation");
            return;
        }

        for (WorkflowListener workflowListener : workflowListeners) {
            if (workflowListener.dispatch(event)) {
                workflowListener.handleEvent(event, context);
            }
        }
    }

    @Override
    public void afterPropertiesSet() {
        eventConsumer.registerHandlers(InnerActivityEventListener.SUPPORTED_EVENT_CODES_SUPPLIER.get(), this);
        eventConsumer.registerHandlers(InnerInstanceEventListener.SUPPORTED_EVENT_CODES_SUPPLIER.get(), this);
        eventConsumer.registerHandlers(InnerNotificationEventListener.SUPPORTED_EVENT_CODES_SUPPLIER.get(), this);
        eventConsumer.registerHandlers(InnerTaskEventListener.SUPPORTED_EVENT_CODES_SUPPLIER.get(), this);
    }

}
