package cn.axzo.workflow.core.engine.listener;

import cn.axzo.framework.jackson.utility.JSON;
import cn.axzo.workflow.core.engine.event.MessagePushEvent;
import cn.axzo.workflow.core.engine.event.MessagePushEventType;
import cn.axzo.workflow.core.listener.BpmnMessagePushEventListener;
import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.AbstractFlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 消息推送事件
 *
 * @author wangli
 * @since 2023/11/22 11:48
 */
@Slf4j
@Component
public class EngineNoticeEventListener extends AbstractFlowableEventListener {

    @Resource
    ObjectProvider<List<BpmnMessagePushEventListener>> processEventListeners;

    public static final Set<MessagePushEventType> NOTICE_PUSH_EVENTS =
            ImmutableSet.<MessagePushEventType>builder()
                    .add(MessagePushEventType.NOTICE)
                    .add(MessagePushEventType.PENDING)
                    .add(MessagePushEventType.SMS)
                    .build();

    @Override
    public void onEvent(FlowableEvent flowableEvent) {

        if (flowableEvent instanceof MessagePushEvent) {
            MessagePushEvent event = (MessagePushEvent) flowableEvent;
            MessagePushEventType pushEventType = (MessagePushEventType) flowableEvent.getType();

            if (NOTICE_PUSH_EVENTS.contains(pushEventType)) {
                switch (pushEventType) {
                    case NOTICE:
                        getOrderedListeners().forEach(i -> i.onNotice(event));
                        break;
                    case PENDING:
                        getOrderedListeners().forEach(i -> i.onPending(event));
                        break;
                    case SMS:
                        getOrderedListeners().forEach(i -> i.onSms(event));
                        break;
                    default:
                }
            }
        }
    }

    private List<BpmnMessagePushEventListener> getOrderedListeners() {
        List<BpmnMessagePushEventListener> orderListeners = new ArrayList<>();
        processEventListeners.ifAvailable(orderListeners::addAll);
        if (log.isDebugEnabled()) {
            log.debug("Order Lists: {}", JSON.toJSONString(orderListeners));
        }
        return orderListeners;
    }


    @Override
    public boolean isFailOnException() {
        return true;
    }

}
