
package cn.orionsec.ops.handler.scheduler;

import cn.orionsec.kit.lang.utils.Exceptions;
import cn.orionsec.kit.lang.utils.Threads;
import cn.orionsec.ops.constant.MessageConst;
import cn.orionsec.ops.constant.SchedulerPools;
import cn.orionsec.ops.constant.scheduler.SchedulerTaskMachineStatus;
import cn.orionsec.ops.handler.scheduler.machine.ITaskMachineHandler;

import java.util.Collection;

public class ParallelTaskProcessor extends AbstractTaskProcessor {

    public ParallelTaskProcessor(Long recordId) {
        super(recordId);
    }

    @Override
    protected void handler() throws Exception {
        // 阻塞执行所有任务
        Collection<ITaskMachineHandler> handlers = this.handlers.values();
        Threads.blockRun(handlers, SchedulerPools.SCHEDULER_TASK_MACHINE_SCHEDULER);
        // 检查是否停止
        if (terminated) {
            return;
        }
        // 全部停止
        final boolean allTerminated = handlers.stream()
                .map(ITaskMachineHandler::getStatus)
                .allMatch(SchedulerTaskMachineStatus.TERMINATED::equals);
        if (allTerminated) {
            this.terminated = true;
            return;
        }
        // 全部成功
        final boolean allSuccess = handlers.stream()
                .map(ITaskMachineHandler::getStatus)
                .filter(s -> !SchedulerTaskMachineStatus.TERMINATED.equals(s))
                .allMatch(SchedulerTaskMachineStatus.SUCCESS::equals);
        if (!allSuccess) {
            throw Exceptions.log(MessageConst.OPERATOR_NOT_ALL_SUCCESS);
        }
    }

    @Override
    public void terminateAll() {
        super.terminateAll();
        handlers.values().forEach(ITaskMachineHandler::terminate);
    }

}
