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) {
        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.getByName(SOURCES_EXTENSION_NAME);

        if (extension == null)
            throw new GradleException("Sources extension isn't found");
        return extension;
    }
}
