package org.implab.gradle.common.sources;

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

/**
 * Registers {@code variants} extension for build-variant modeling.
 */
public abstract class VariantsPlugin implements Plugin<Project> {
    private static final Logger logger = Logging.getLogger(VariantsPlugin.class);
    public static final String VARIANTS_EXTENSION_NAME = "variants";

    @Override
    public void apply(Project target) {
        logger.debug("Registering '{}' extension on project '{}'", VARIANTS_EXTENSION_NAME, target.getPath());
        var variants = target.getExtensions().create(VARIANTS_EXTENSION_NAME, BuildVariantsExtension.class);
        target.afterEvaluate(project -> {
            logger.debug("Finalizing variants model on project '{}'", project.getPath());
            variants.finalizeModel();
            logger.debug("Variants model finalized on project '{}'", project.getPath());
        });
    }

    public static BuildVariantsExtension getVariantsExtension(Project target) {
        var extension = target.getExtensions().findByType(BuildVariantsExtension.class);

        if (extension == null) {
            logger.error("Variants extension '{}' isn't found on project '{}'", VARIANTS_EXTENSION_NAME, target.getPath());
            throw new GradleException("Variants extension isn't found");
        }

        logger.debug("Resolved '{}' extension on project '{}'", VARIANTS_EXTENSION_NAME, target.getPath());

        return extension;
    }
}
