package com.atlassian.bitbucket.mesh.git.merge;

import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

public class MapMergeStrategyFactory implements MergeStrategyFactory {

    private final Map<GitMergeStrategy, MergeStrategy> strategies;

    public MapMergeStrategyFactory(Map<GitMergeStrategy, MergeStrategy> strategies) {
        this.strategies = ImmutableMap.copyOf(strategies);

        //Sanity check for the future
        List<GitMergeStrategy> missingStrategies = Arrays.stream(GitMergeStrategy.values())
                .filter(((Predicate<GitMergeStrategy>) strategies::containsKey).negate())
                .collect(toList());
        if (!missingStrategies.isEmpty()) {
            throw new IllegalStateException("One or more strategies have not been registered: " + missingStrategies);
        }
    }

    @Nonnull
    @Override
    public MergeStrategy create(@Nonnull GitMergeStrategy strategy) {
        //This can't miss; the constructor ensures every strategy is mapped
        return strategies.get(requireNonNull(strategy));
    }
}
