package ru.yandex.canvas.service.multitype;

import java.util.List;
import java.util.Map;

import com.google.errorprone.annotations.ForOverride;

import ru.yandex.canvas.model.CreativeWithId;
import ru.yandex.canvas.service.multitype.singletype.request.SingleCreativeTypeOperationRequest;

public abstract class SingleCreativeTypeIdsByClientOperation<T extends CreativeWithId,
        R extends SingleCreativeTypeOperationRequest> extends SingleCreativeTypeBaseOperation<T, R> {
    @ForOverride
    public abstract List<OnCreativeOperationResult> process(Long clientId, List<T> creatives);

    @Override
    public void run(R request, Map<Long, OnCreativeOperationResult> result) {
        List<Long> creativeIds = request.getCreativeIds();
        Map<Long, List<T>> creativesByClientId = getOnCreativeService().fetchForTypeByIdsGroupedByClient(creativeIds);
        getLogger().info("SingleTypeOperation on " + worksOn() + " fetched ids: ", creativesByClientId);
        long fetchedAmount = creativesByClientId.values().stream().flatMap(cs -> cs.stream()).count();
        if (creativeIds.size() != fetchedAmount) {
            throw new IllegalStateException("Fetched creatives not match ids list");
        }

        for (Long clientId : creativesByClientId.keySet()) {
            List<T> creatives = creativesByClientId.get(clientId);
            List<OnCreativeOperationResult> resultsList = process(clientId, creatives);
            checkAndMergeResults(creatives, resultsList, result);
        }
    }
}
