/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.channel.cc.orchestrator.commons.polling;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

import com.scytl.products.ov.channel.cc.orchestrator.commons.infrastructure.persistence.PartialResultsRepository;

/**
 * Basic abstract implementation of {@link ResultsHandler}.
 *
 * @param <T>
 *            the type of the result.
 */
public abstract class AbstractPartialResultsHandler<T>
        implements ResultsHandler<List<T>> {

    private final PartialResultsRepository<T> repository;

    /**
     * Constructor.
     * 
     * @param repository
     */
    public AbstractPartialResultsHandler(
            PartialResultsRepository<T> repository) {
        this.repository = repository;
    }

    @Override
    public final Optional<List<T>> handleResultsIfReady(
            UUID correlationId) {
        int count = getPartialResultsCount();
        Optional<List<T>> results =
            repository.listIfHasAll(correlationId, count);
        if (results.isPresent()) {
            repository.deleteAll(correlationId);
            return results;
        }
        return Optional.empty();
    }

    protected abstract int getPartialResultsCount();
}
