package cn.axzo.workflow.starter.handler.execute;

import cn.axzo.framework.domain.ServiceException;
import cn.axzo.workflow.starter.handler.execute.interceptor.ExecuteInterceptor;

import java.util.List;
import java.util.function.Consumer;

public final class ListenerExecutor {

    private final ExecuteInterceptor firstExecuteInterceptor;

    public ListenerExecutor(List<ExecuteInterceptor> chain) {
        this.firstExecuteInterceptor = initInterceptorChain(chain);
    }

    public <T> void execute(Consumer<T> command, T t) {
        firstExecuteInterceptor.execute(this, command, t);
    }

    private ExecuteInterceptor initInterceptorChain(List<ExecuteInterceptor> chain) {
        if (chain == null || chain.isEmpty()) {
            throw new ServiceException("invalid command interceptor chain configuration: " + chain);
        }
        for (int i = 0; i < chain.size() - 1; i++) {
            chain.get(i).setNext(chain.get(i + 1));
        }
        return chain.get(0);
    }
}
