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

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

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.gradle.api.Action;
import org.implab.gradle.common.sources.GenericSourceSet;
import org.implab.gradle.variants.core.Layer;
import org.implab.gradle.variants.core.Variant;
import org.implab.gradle.variants.sources.CompileUnit;

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

    public void addLayerAction(Layer layer, Action<? super GenericSourceSet> action) {
        actionsByLayer.computeIfAbsent(layer, key -> new ArrayList<>()).add(action);
    }

    public void addVariantAction(Variant variant, Action<? super GenericSourceSet> action) {
        actionsByVariant.computeIfAbsent(variant, key -> new ArrayList<>()).add(action);
    }

    public void addUnitAction(CompileUnit unit, Action<? super GenericSourceSet> action) {
        actionsByUnit.computeIfAbsent(unit, 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);
    }
}
