package ru.yandex.webmaster3.worker;

import org.apache.commons.lang3.mutable.MutableInt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.common.util.concurrent.CarefulExecutorService;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.worker.task.AccumullablePeriodicTaskState;
import ru.yandex.webmaster3.storage.host.AllHostsCacheService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


public abstract class CommonHostsIteratingPeriodicTask<TS extends AccumullablePeriodicTaskState<TS>> extends PeriodicTask<TS> {
    protected Logger log = LoggerFactory.getLogger(getClass());
    private AllHostsCacheService allHostsCacheService;

    protected void doRun(int totalThreads) throws Exception {
        ExecutorService executorService = ru.yandex.common.util.concurrent.Executors.newBlockingFixedThreadPool(
                totalThreads, totalThreads,
                0, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(totalThreads),
                Executors.defaultThreadFactory());
        List<Future<TS>> futures = new ArrayList<>();
        allHostsCacheService.processKeyBatch((List<WebmasterHostId> batch) -> {
            var batchCopy = new ArrayList<>(batch);
            futures.add(executorService.submit(() -> processBatch(batchCopy)));
        }, 5000);

        for (Future<TS> f : futures) {
            state.accumulate(f.get());
        }

        executorService.shutdownNow();
    }

    protected abstract TS processBatch(List<WebmasterHostId> list);

    @Required
    public void setAllHostsCacheService(AllHostsCacheService allHostsCacheService) {
        this.allHostsCacheService = allHostsCacheService;
    }
}