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

import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.NamedDomainObjectProvider;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.api.provider.Provider;
import org.implab.gradle.variants.artifacts.OutgoingConfiguration;
import org.implab.gradle.variants.artifacts.Slot;
import org.implab.gradle.variants.core.Variant;

class DefaultOutgoingConfiguration implements OutgoingConfiguration {

    private final Variant variant;

    private final NamedDomainObjectProvider<Configuration> configurationProvider;

    private final NamedDomainObjectContainer<Slot> slots;

    private final Property<Slot> primarySlot;

    public DefaultOutgoingConfiguration(
            Variant variant,
            NamedDomainObjectProvider<Configuration> configurationProvider,
            ObjectFactory objectFactory,
            ProviderFactory providerFactory) {
        this.variant = variant;
        this.configurationProvider = configurationProvider;
        this.slots = objectFactory.domainObjectContainer(Slot.class);
        this.primarySlot = objectFactory.property(Slot.class)
                .convention(providerFactory
                        .provider(this::primarySlotConvention)
                        .flatMap(x -> x));
    }

    @Override
    public Property<Slot> getPrimarySlot() {
        return primarySlot;
    }

    @Override
    public Variant getVariant() {
        return variant;
    }

    @Override
    public NamedDomainObjectProvider<Configuration> getOutgoingConfiguration() {
        return configurationProvider;
    }

    @Override
    public NamedDomainObjectContainer<Slot> getSlots() {
        return slots;
    }

    private Provider<Slot> primarySlotConvention() {
        return slots.size() == 1 ? slots.named(slots.getNames().first()) : null;
    }

}
