package org.implab.gradle.common.sources;

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

/**
 * This plugin creates a {@code sources} extension which is
 * a container for {@link GenericSourceSet}.
 *
 */
public abstract class SourcesPlugin implements Plugin<Project> {
    private static final Logger logger = Logging.getLogger(SourcesPlugin.class);

    private static final String SOURCES_EXTENSION_NAME = "sources";

    @Override
    public void apply(Project target) {
        logger.debug("Registering '{}' extension on project '{}'", SOURCES_EXTENSION_NAME, target.getPath());
        var sources = target.getObjects().domainObjectContainer(GenericSourceSet.class);
        target.getExtensions().add(SOURCES_EXTENSION_NAME, sources);
    }

    public static NamedDomainObjectContainer<GenericSourceSet> getSourcesExtension(Project target) {
        var extensions = target.getExtensions();

        @SuppressWarnings("unchecked")
        var extension = (NamedDomainObjectContainer<GenericSourceSet>) extensions.findByName(SOURCES_EXTENSION_NAME);

        if (extension == null) {
            logger.error("Sources extension '{}' isn't found on project '{}'", SOURCES_EXTENSION_NAME, target.getPath());
            throw new GradleException("Sources extension isn't found");
        }
        logger.debug("Resolved '{}' extension on project '{}'", SOURCES_EXTENSION_NAME, target.getPath());
        return extension;
    }
}
