package org.implab.gradle.variants.sources.internal;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.gradle.api.Action;
import org.implab.gradle.common.sources.GenericSourceSet;
import org.implab.gradle.variants.core.Layer;
import org.implab.gradle.variants.derived.CompileUnit;

public class DefaultLayerConfigurationRegistry implements LayerConfigurationRegistry {
    private final Map<Layer, List<Action<? super GenericSourceSet>>> actionsByLayer = new LinkedHashMap<>();

    @Override
    public void add(Layer layer, Action<? super GenericSourceSet> action) {
        Objects.requireNonNull(layer, "layer can't be null");
        Objects.requireNonNull(action, "action can't be null");
        actionsByLayer.computeIfAbsent(layer, key -> new ArrayList<>()).add(action);
    }

    @Override
    public void applyLayer(Layer layer, GenericSourceSet sourceSet) {
        var actions = actionsByLayer.get(layer);
        if (actions == null) {
            return;
        }
        for (var action : actions) {
            action.execute(sourceSet);
        }
    }

    @Override
    public void applyUnit(CompileUnit unit, GenericSourceSet sourceSet) {
        applyLayer(unit.layer(), sourceSet);
    }
}
