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

import cn.axzo.workflow.core.engine.event.BizSpecifyAssigneeEvent;
import cn.axzo.workflow.core.engine.event.BizSpecifyAssigneeEventType;
import cn.axzo.workflow.core.listener.BpmnActivityEventListener;
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;

import static cn.axzo.workflow.core.engine.event.BizSpecifyAssigneeEventType.ADD_ASSIGNEE;
import static cn.axzo.workflow.core.engine.event.BizSpecifyAssigneeEventType.REMOVE_ASSIGNEE;
import static cn.axzo.workflow.core.engine.event.BizSpecifyAssigneeEventType.UPDATE_ASSIGNEE;

/**
 * Activity 节点的扩展事件, 用于处理业务节点通知业务添加审批人
 *
 * @author wangli
 * @since 2023/12/21 11:25
 */
@Slf4j
@Component
public class EngineActivityExtEventListener extends AbstractFlowableEventListener {

    @Resource
    ObjectProvider<List<BpmnActivityEventListener>> activityListeners;

    public static final Set<BizSpecifyAssigneeEventType> BIZ_SPECIFY_ASSIGNEE_EVENTS =
            ImmutableSet.<BizSpecifyAssigneeEventType>builder()
                    .add(ADD_ASSIGNEE)
                    .add(UPDATE_ASSIGNEE)
                    .add(REMOVE_ASSIGNEE)
                    .build();

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        if (flowableEvent instanceof BizSpecifyAssigneeEvent) {
            BizSpecifyAssigneeEvent event = (BizSpecifyAssigneeEvent) flowableEvent;
            BizSpecifyAssigneeEventType type = (BizSpecifyAssigneeEventType) event.getType();
            if (BIZ_SPECIFY_ASSIGNEE_EVENTS.contains(type)) {
                switch (type) {
                    case ADD_ASSIGNEE:
                        getOrderedListeners().forEach(i -> i.onWaitAssignee(event));
                        break;
                    case UPDATE_ASSIGNEE:
                        break;
                    case REMOVE_ASSIGNEE:
                        break;
                    default:
                }
            }
        }
    }

    private List<BpmnActivityEventListener> getOrderedListeners() {
        List<BpmnActivityEventListener> orderListeners = new ArrayList<>();
        activityListeners.ifAvailable(orderListeners::addAll);
        return orderListeners;
    }

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