package ru.yandex.webmaster3.core.util.concurrent.graph;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.core.util.RetryUtils;
import ru.yandex.webmaster3.core.util.functional.ThrowingFunction;

import java.util.List;

/**
 * @author avhaliullin
 */
public class MappingConsumerImpl<In, Out> implements BlockingBatchConsumer<In> {
    private static final Logger log = LoggerFactory.getLogger(MappingConsumerImpl.class);

    private final ThrowingFunction<In, Out, Exception> mapper;
    private final RetryUtils.RetryPolicy retryPolicy;
    private final FailPolicy failPolicy;
    private final GraphOutQueue<Out> out;

    public MappingConsumerImpl(GraphOutQueue<Out> out, RetryUtils.RetryPolicy retryPolicy, FailPolicy failPolicy, ThrowingFunction<In, Out, Exception> mapper) {
        this.mapper = mapper;
        this.retryPolicy = retryPolicy;
        this.failPolicy = failPolicy;
        this.out = out;
    }

    @Override
    public void accept(List<In> batch) throws Exception {
        for (In item : batch) {
            Out result = null;
            try {
                result = RetryUtils.query(retryPolicy, () -> mapper.apply(item));
            } catch (Exception e) {
                failPolicy.handle(e);
            }
            if (result != null) {
                out.put(result);
            }
        }
    }


}
