package org.implab.gradle.common.sources;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;

/**
 * Binds variant layers to registered source sets.
 */
public abstract class VariantsSourcesPlugin implements Plugin<Project> {
    private static final Logger logger = Logging.getLogger(VariantsSourcesPlugin.class);
    public static final String VARIANT_SOURCES_EXTENSION_NAME = "variantSources";

    @Override
    public void apply(Project target) {
        logger.debug("Applying variant-sources plugin on project '{}'", target.getPath());
        target.getPluginManager().apply(VariantsPlugin.class);
        target.getPluginManager().apply(SourcesPlugin.class);

        var variants = VariantsPlugin.getVariantsExtension(target);
        var sources = SourcesPlugin.getSourcesExtension(target);

        var variantSources = target.getExtensions()
                .create(VARIANT_SOURCES_EXTENSION_NAME, VariantSourcesExtension.class);

        variants.whenFinalized(model -> {
            logger.debug("Registering source sets for variants on project '{}'", target.getPath());
            variantSources.registerSourceSets(model, sources);
            logger.debug("Registered source sets on project '{}'", target.getPath());
        });
    }
}
