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

import org.gradle.api.Action;
import org.gradle.api.model.ObjectFactory;
import org.implab.gradle.variants.artifacts.ArtifactAssemblySpec;
import org.implab.gradle.variants.artifacts.ArtifactSlot;
import org.implab.gradle.variants.artifacts.OutgoingVariant;
import org.implab.gradle.variants.artifacts.Slot;
import org.implab.gradle.variants.artifacts.VariantArtifactsSpec;

class DefaultVariantArtifactSpec implements VariantArtifactsSpec {

    private final ObjectFactory objectFactory;
    private final ArtifactConfigurationHandler assemblyBuilder;

    private final OutgoingVariant outgoingVariant;

    DefaultVariantArtifactSpec(
            OutgoingVariant outgoingVariant,
            ObjectFactory objectFactory,
            ArtifactConfigurationHandler assemblyBuilder) {
        this.objectFactory = objectFactory;
        this.assemblyBuilder = assemblyBuilder;
        this.outgoingVariant = outgoingVariant;
    }

    @Override
    public void slot(String name, Action<? super ArtifactAssemblySpec> action) {
        var slot = outgoingVariant.getSlots().maybeCreate(name);

        configureSlot(slot, action);
    }

    @Override
    public void primarySlot(String name, Action<? super ArtifactAssemblySpec> action) {
        var slot = outgoingVariant.getSlots().maybeCreate(name);
        outgoingVariant.getPrimarySlot().set(slot);

        configureSlot(slot, action);
    }

    private void configureSlot(Slot slot, Action<? super ArtifactAssemblySpec> action) {
        var artifactSlot = new ArtifactSlot(outgoingVariant.getVariant(), slot);

        var inputsAssembler = assemblyBuilder.slotAssembler(artifactSlot);

        var spec = new DefaultArtifactAssemblySpec(objectFactory, inputsAssembler.consumer());
        action.execute(spec);
    }

}
