/*
 * Copyright 2017 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.api.internal.project;

import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.internal.DefaultMutationGuard;
import org.gradle.api.internal.MutationGuard;
import org.gradle.api.internal.WithMutationGuard;
import org.gradle.internal.Actions;
import org.gradle.internal.operations.BuildOperationContext;
import org.gradle.internal.operations.BuildOperationDescriptor;
import org.gradle.internal.operations.BuildOperationExecutor;
import org.gradle.internal.operations.RunnableBuildOperation;

import java.util.Collections;

public class BuildOperationCrossProjectConfigurator implements CrossProjectConfigurator, WithMutationGuard {

    private final BuildOperationExecutor buildOperationExecutor;
    private final MutationGuard mutationGuard = new DefaultMutationGuard();

    public BuildOperationCrossProjectConfigurator(BuildOperationExecutor buildOperationExecutor) {
        this.buildOperationExecutor = buildOperationExecutor;
    }

    @Override
    public Project project(Project project, Action<? super Project> configureAction) {
        runProjectConfigureActionWithMutationLock(project, configureAction);
        return project;
    }

    @Override
    public void subprojects(Iterable<Project> projects, Action<? super Project> configureAction) {
        runBlockConfigureAction(BlockConfigureBuildOperation.SUBPROJECTS_DETAILS, projects, configureAction, true);
    }

    @Override
    public void allprojects(Iterable<Project> projects, Action<? super Project> configureAction) {
        runBlockConfigureAction(BlockConfigureBuildOperation.ALLPROJECTS_DETAILS, projects, configureAction, true);
    }

    @Override
    public Project rootProject(Project project, Action<Project> buildOperationExecutor) {
        // TODO We don't fire rootProject blocks with the project mutation lock because they fire in projectsLoaded which is too early for the project to be registerd in ProjectRegistry
        runBlockConfigureAction(BlockConfigureBuildOperation.ROOT_PROJECT_DETAILS, Collections.singleton(project), buildOperationExecutor, false);
        return project;
    }

    private void runBlockConfigureAction(final BuildOperationDescriptor.Builder details, final Iterable<Project> projects, final Action<? super Project> configureAction, final boolean withMutationLock) {
        buildOperationExecutor.run(new BlockConfigureBuildOperation(details, projects) {
            @Override
            protected void doRunProjectConfigure(Project project) {
                if (withMutationLock) {
                    runProjectConfigureActionWithMutationLock(project, configureAction);
                } else {
                    runProjectConfigureAction(project, configureAction);
                }
            }
        });
    }

    private void runProjectConfigureActionWithMutationLock(final Project project, final Action<? super Project> configureAction) {
        ((ProjectInternal)project).getMutationState().withMutableState(new Runnable() {
            @Override
            public void run() {
                runProjectConfigureAction(project, configureAction);
            }
        });
    }

    private void runProjectConfigureAction(final Project project, final Action<? super Project> configureAction) {
        buildOperationExecutor.run(new CrossConfigureProjectBuildOperation(project) {
            @Override
            public void run(BuildOperationContext context) {
                Actions.with(project, mutationGuard.withMutationEnabled(configureAction));
            }
        });
    }

    @Override
    public MutationGuard getMutationGuard() {
        return mutationGuard;
    }

    private static abstract class BlockConfigureBuildOperation implements RunnableBuildOperation {

        private final static String ALLPROJECTS = "allprojects";
        private final static String SUBPROJECTS = "subprojects";
        private final static String ROOTPROJECT = "rootProject";

        private final static BuildOperationDescriptor.Builder ALLPROJECTS_DETAILS = computeConfigurationBlockBuildOperationDetails(ALLPROJECTS);
        private final static BuildOperationDescriptor.Builder SUBPROJECTS_DETAILS = computeConfigurationBlockBuildOperationDetails(SUBPROJECTS);
        private final static BuildOperationDescriptor.Builder ROOT_PROJECT_DETAILS = computeConfigurationBlockBuildOperationDetails(ROOTPROJECT);

        private final BuildOperationDescriptor.Builder details;
        private final Iterable<Project> projects;

        private BlockConfigureBuildOperation(BuildOperationDescriptor.Builder details, Iterable<Project> projects) {
            this.details = details;
            this.projects = projects;
        }

        private static BuildOperationDescriptor.Builder computeConfigurationBlockBuildOperationDetails(String configurationBlockName) {
            return BuildOperationDescriptor.displayName("Execute '" + configurationBlockName + " {}' action").name(configurationBlockName);
        }

        @Override
        public BuildOperationDescriptor.Builder description() {
            return details;
        }

        @Override
        public void run(BuildOperationContext context) {
            for (Project project : projects) {
                doRunProjectConfigure(project);
            }
        }

        abstract void doRunProjectConfigure(Project project);
    }

    private static abstract class CrossConfigureProjectBuildOperation implements RunnableBuildOperation {
        private Project project;

        private CrossConfigureProjectBuildOperation(Project project) {
            this.project = project;
        }

        @Override
        public BuildOperationDescriptor.Builder description() {
            String name = "Cross-configure project " + ((ProjectInternal) project).getIdentityPath().toString();
            return BuildOperationDescriptor.displayName(name);
        }
    }
}

@@ -1733,32 +1733,16 @@
 reAction
-WithMutationLock
 (project
@@ -2004,38 +2004,32 @@
  configureAction
-, true
 );%0A    %7D%0A%0A    @O
@@ -2246,14 +2246,8 @@
 tion
-, true
 );%0A 
@@ -2360,194 +2360,8 @@
 ) %7B%0A
-        // TODO We don't fire rootProject blocks with the project mutation lock because they fire in projectsLoaded which is too early for the project to be registerd in ProjectRegistry%0A
     
@@ -2497,15 +2497,8 @@
 utor
-, false
 );%0A 
@@ -2699,40 +2699,8 @@
 tion
-, final boolean withMutationLock
 ) %7B%0A
@@ -2882,52 +2882,8 @@
 ) %7B%0A
-                if (withMutationLock) %7B%0A    
     
@@ -2919,32 +2919,16 @@
 reAction
-WithMutationLock
 (project
@@ -2951,124 +2951,8 @@
 n);%0A
-                %7D else %7B%0A                    runProjectConfigureAction(project, configureAction);%0A                %7D%0A
     
@@ -3026,24 +3026,8 @@
 tion
-WithMutationLock
 (fin
@@ -3249,217 +3249,8 @@
     
-        runProjectConfigureAction(project, configureAction);%0A            %7D%0A        %7D);%0A    %7D%0A%0A    private void runProjectConfigureAction(final Project project, final Action%3C? super Project%3E configureAction) %7B%0A
     
@@ -3335,32 +3335,40 @@
 ) %7B%0A            
+ 
+       
 @Override%0A      
@@ -3353,32 +3353,40 @@
       @Override%0A
+        
             publ
@@ -3446,16 +3446,24 @@
         
+       
+ 
 Actions.
@@ -3529,16 +3529,58 @@
 tion));%0A
+                    %7D%0A                %7D);%0A
         

Remove workaround for mutation guard early in the build