/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gradle.language.base.plugins;

import org.gradle.api.*;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.tasks.TaskContainer;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.language.base.ProjectSourceSet;
import org.gradle.language.base.internal.DefaultProjectSourceSet;
import org.gradle.language.base.internal.tasks.AssembleBinariesTask;
import org.gradle.model.Model;
import org.gradle.model.Mutate;
import org.gradle.model.RuleSource;
import org.gradle.model.collection.CollectionBuilder;
import org.gradle.model.collection.internal.BridgedCollections;
import org.gradle.model.internal.core.ModelPath;
import org.gradle.model.internal.registry.ModelRegistry;
import org.gradle.model.internal.type.ModelType;
import org.gradle.platform.base.BinaryContainer;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.internal.BinarySpecInternal;
import org.gradle.platform.base.internal.DefaultBinaryContainer;

import javax.inject.Inject;

/**
 * Base plugin for language support.
 *
 * Adds a {@link org.gradle.platform.base.BinaryContainer} named {@code binaries} to the project. Adds a {@link org.gradle.language.base.ProjectSourceSet} named {@code sources} to the project.
 *
 * For each binary instance added to the binaries container, registers a lifecycle task to create that binary.
 */
@Incubating
public class LanguageBasePlugin implements Plugin<Project> {

    private final Instantiator instantiator;
    private final ModelRegistry modelRegistry;

    @Inject
    public LanguageBasePlugin(Instantiator instantiator, ModelRegistry modelRegistry) {
        this.instantiator = instantiator;
        this.modelRegistry = modelRegistry;
    }

    public void apply(final Project target) {
        target.getPluginManager().apply(LifecycleBasePlugin.class);
        target.getExtensions().create("sources", DefaultProjectSourceSet.class);

        DefaultBinaryContainer binaries = target.getExtensions().create("binaries", DefaultBinaryContainer.class, instantiator);
        String descriptor = getClass().getName() + ".apply()";
        modelRegistry.create(
                BridgedCollections.dynamicTypes(
                        ModelType.of(DefaultBinaryContainer.class),
                        ModelType.of(DefaultBinaryContainer.class),
                        ModelType.of(BinarySpec.class),
                        ModelPath.path("binaries"),
                        binaries,
                        Named.Namer.INSTANCE,
                        descriptor,
                        BridgedCollections.itemDescriptor(descriptor)
                ),
                ModelPath.ROOT
        );
    }

    /**
     * Model rules.
     */
    @SuppressWarnings("UnusedDeclaration")
    static class Rules extends RuleSource {
        @Model
        ProjectSourceSet sources(ExtensionContainer extensions) {
            return extensions.getByType(ProjectSourceSet.class);
        }

        @Mutate
        void createLifecycleTaskForBinary(TaskContainer tasks, BinaryContainer binaries) {
            for (BinarySpecInternal binary : binaries.withType(BinarySpecInternal.class)) {
                if (!binary.isLegacyBinary()) {
                    Task binaryLifecycleTask = tasks.create(binary.getName());
                    binaryLifecycleTask.setGroup(LifecycleBasePlugin.BUILD_GROUP);
                    binaryLifecycleTask.setDescription(String.format("Assembles %s.", binary));
                    binary.setBuildTask(binaryLifecycleTask);
                }
            }
        }

        @Mutate
        void attachBinariesToAssembleLifecycle(CollectionBuilder<Task> tasks, final BinaryContainer binaries) {
            tasks.named("assemble", new Action<Task>() {
                @Override
                public void execute(Task assemble) {
                    for (BinarySpecInternal binary : binaries.withType(BinarySpecInternal.class)) {
                        if (!binary.isLegacyBinary()) {
                            if (binary.isBuildable()) {
                                assemble.dependsOn(binary);
                            } else {
                                ((AssembleBinariesTask) assemble).notBuildable(binary);
                            }
                        }
                    }
                }
            });
        }
    }
}

@@ -4195,39 +4195,35 @@
      %7D%0A%0A        
-@Mutate
+/**
 %0A        void at
@@ -4219,124 +4219,38 @@
     
-void attachBinariesToAssembleLifecycle(CollectionBuilder%3CTask%3E tasks, final BinaryContainer binaries) %7B%0A
+ * Rules.%0A     
     
+*/%0A
         
 task
@@ -4249,50 +4249,52 @@
     
+s
 ta
-sks.named(%22assemble%22, new Action%3CTask%3E()
+tic class AssembleRule extends RuleSource
  %7B%0A 
@@ -4308,20 +4308,14 @@
     
-    @Overrid
+@Mutat
 e%0A  
@@ -4328,53 +4328,70 @@
     
-    public void execute(Task assemble) %7B%0A    
+void addDependency(Task assemble, BinaryContainer binaries) %7B%0A
     
@@ -4494,36 +4494,32 @@
                 
-    
 if (!binary.isLe
@@ -4554,28 +4554,24 @@
             
- 
-   
 if (binary.i
@@ -4582,28 +4582,24 @@
 ldable()) %7B%0A
-    
             
@@ -4666,20 +4666,16 @@
         
-    
 %7D else %7B
@@ -4703,20 +4703,16 @@
         
-   
- 
 ((Assemb
@@ -4775,36 +4775,32 @@
                 
-    
 %7D%0A              
@@ -4787,32 +4787,44 @@
     %7D%0A          
+          %7D%0A
               %7D%0A
@@ -4817,34 +4817,28 @@
             
-%7D%0A      
   
+%7D%0A
             
@@ -4847,39 +4847,201 @@
         
-        %7D%0A            %7D
+%7D%0A%0A        @Mutate%0A        void attachBinariesToAssembleLifecycle(CollectionBuilder%3CTask%3E tasks, final BinaryContainer binaries) %7B%0A            tasks.named(%22assemble%22, AssembleRule.class
 );%0A     

Make the assemble task depend on the binary container, instead of having the task container depend on it.