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

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ProviderFactory;
import org.implab.gradle.variants.artifacts.OutgoingConfiguration;
import org.implab.gradle.variants.core.Variant;

public class OutgoingRegistry {
    private final Map<Variant, DefaultOutgoingConfiguration> outgoingByVariant = new LinkedHashMap<>();

    private final ConfigurationContainer configurations;
    private final ObjectFactory objects;
    private final ProviderFactory providers;

    public OutgoingRegistry(ConfigurationContainer configurations, ObjectFactory objects, ProviderFactory providers) {
        this.configurations = configurations;
        this.objects = objects;
        this.providers = providers;
    }

    public Optional<OutgoingConfiguration> findOutgoing(Variant variant) {
        return Optional.ofNullable(outgoingByVariant.get(variant));
    }

    public OutgoingConfiguration maybeCreate(Variant variant) {
        return outgoingByVariant.computeIfAbsent(variant, this::newOutgoingConfiguration);
    }

    private DefaultOutgoingConfiguration newOutgoingConfiguration(Variant variant) {
        var configuration = configurations.register(outgoingConfigurationName(variant));

        return new DefaultOutgoingConfiguration(variant, configuration, objects, providers);
    }

    String outgoingConfigurationName(Variant variant) {
        return variant.getName() + "Elements";
    }


}
