/*
 * Copyright (C) 2019-2022 LitterBox contributors
 *
 * This file is part of LitterBox.
 *
 * LitterBox is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * LitterBox is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LitterBox. If not, see <http://www.gnu.org/licenses/>.
 */
package de.uni_passau.fim.se2.litterbox.refactor.metaheuristics.chromosomes;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toCollection;

/**
 * A generator for populations of fixed size.
 *
 * @param <C> the type of chromosomes contained in the population
 */
public class FixedSizePopulationGenerator<C extends Chromosome<C>> implements Supplier<List<C>> {

    /**
     * The generator with which to generate individual chromosomes.
     */
    private final ChromosomeGenerator<C> chromosomes;

    /**
     * The size of the population this generator creates.
     */
    private final int populationSize;

    /**
     * Creates a new population generator that uses the given chromosome generator to create
     * individual chromosomes of the population, while respecting the specified population size.
     *
     * @param chromosomeGenerator generator for individual chromosomes, {@code not null}
     * @param populationSize      size of the population generated by this population generator
     * @throws NullPointerException     if the chromosome generator is {@code null}
     * @throws IllegalArgumentException if the population size is negative
     */
    public FixedSizePopulationGenerator(
            final ChromosomeGenerator<C> chromosomeGenerator,
            final int populationSize) {
        Objects.requireNonNull(chromosomeGenerator);

        if (populationSize < 0) {
            throw new IllegalArgumentException("negative population size: " + populationSize);
        }

        this.chromosomes = chromosomeGenerator;
        this.populationSize = populationSize;
    }

    /**
     * Returns the fixed size of the populations generated by this generator.
     *
     * @return the size of a population
     */
    public int getPopulationSize() {
        return populationSize;
    }

    /**
     * Generates a new population of fixed size.
     *
     * @return the generated population
     */
    @Override
    public List<C> get() {
        return Stream.generate(chromosomes)
                .limit(populationSize)
                .collect(toCollection(ArrayList::new));
    }
}
