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

import org.gradle.api.Action;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.provider.ProviderFactory;
import org.implab.gradle.variants.artifacts.OutgoingVariant;

public class SingleSlotConvention implements Action<OutgoingVariant> {

    private final ProviderFactory providers;

    public SingleSlotConvention(ProviderFactory providers) {
        this.providers = providers;
    }

    @Override
    public void execute(OutgoingVariant outgoingVariant) {
        var slots = outgoingVariant.getSlots();

        outgoingVariant.getPrimarySlot().convention(
                // If exactly one slot is declared, it becomes the primary slot.
                providers.provider(() -> {
                    if (slots.size() == 0)
                        throw new InvalidUserDataException("No slots declared for " + outgoingVariant.getVariant());
                    if (slots.size() > 1)
                        throw new InvalidUserDataException("Multiple slots declared for " + outgoingVariant.getVariant() +
                                ", please specify primary slot explicitly");

                    return slots.stream().findAny().get();
                }));
    }

}
