/*
 * Copyright 2022 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.internal.execution;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.gradle.api.GradleException;
import org.gradle.internal.exceptions.Contextual;
import org.gradle.internal.logging.text.TreeFormatter;
import org.gradle.model.internal.type.ModelType;

import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * A {@code WorkValidationException} is thrown when there is some validation problem with a work item.
 */
@Contextual
public class WorkValidationException extends GradleException {
    private static final int MAX_ERR_COUNT = Integer.getInteger("org.gradle.internal.max.validation.errors", 5);

    private final List<String> problems;

    private WorkValidationException(String message, Collection<String> problems) {
        super(message);
        this.problems = ImmutableList.copyOf(problems);
    }

    public List<String> getProblems() {
        return problems;
    }

    public static Builder forProblems(Collection<String> problems) {
        return new Builder(problems);
    }

    /**
     * A Stepwise builder for a {@code WorkValidationException}.
     *
     * This class represents step 1, call {@link #withSummaryForContext(String, WorkValidationContext)} or {@link #withSummaryForPlugin()} to return Step 2.
     */
    public final static class Builder {
        private final List<String> problems;

        public Builder(Collection<String> problems) {
            this.problems = problems.stream().limit(MAX_ERR_COUNT).collect(ImmutableList.toImmutableList());
        }

        public Builder limitTo(int maxProblems) {
            return new Builder(problems.stream().limit(maxProblems).collect(Collectors.toList()));
        }

        public BuilderWithSummary withSummaryForContext(String validatedObjectName, WorkValidationContext validationContext) {
            ValidationErrorSummarizer summarizer = new ValidationErrorSummarizer(validatedObjectName, validationContext);
            return new BuilderWithSummary(problems, summarizer.apply(problems));
        }

        public BuilderWithSummary withSummaryForPlugin() {
            String summary = "Plugin validation failed with " + problems.size() + " problem" + (problems.size() == 1 ? "" : "s");
            return new BuilderWithSummary(problems, summary);
        }

        /**
         * This function can build a formatted String summarizing a list of problems.
         */
        public static final class ValidationErrorSummarizer implements Function<List<String>, String> {
            private final String validatedObjectName;
            private final WorkValidationContext validationContext;

            public ValidationErrorSummarizer(String validatedObjectName, WorkValidationContext validationContext) {
                this.validatedObjectName = validatedObjectName;
                this.validationContext = validationContext;
            }

            @Override
            public String apply(List<String> problems) {
                return String.format("%s found with the configuration of %s (%s).",
                        problems.size() == 1 ? "A problem was" : "Some problems were",
                        validatedObjectName,
                        describeTypesChecked(validationContext.getValidatedTypes()));
            }

            private String describeTypesChecked(ImmutableCollection<Class<?>> types) {
                return types.size() == 1
                        ? "type '" + getTypeDisplayName(types.iterator().next()) + "'"
                        : "types '" + types.stream().map(this::getTypeDisplayName).collect(Collectors.joining("', '")) + "'";
            }

            private String getTypeDisplayName(Class<?> type) {
                return ModelType.of(type).getDisplayName();
            }
        }
    }

    /**
     * A builder for a {@code WorkValidationException} that has a summary attached.
     *
     * The {@link WorkValidationException#Builder} class is a Stepwise builder, this is step 2.
     */
    public final static class BuilderWithSummary {
        private final List<String> problems;
        private final String summary;

        public BuilderWithSummary(List<String> problems, String summary) {
            this.problems = problems;
            this.summary = summary;
        }

        public WorkValidationException get() {
            return build(null);
        }

        public WorkValidationException getWithExplanation(String explanation) {
            return build(explanation);
        }

        private WorkValidationException build(@Nullable String explanation) {
            TreeFormatter formatter = new TreeFormatter();
            formatter.node(summary);
            formatter.startChildren();
            for (String problem : problems) {
                formatter.node(problem);
            }
            formatter.endChildren();
            if (explanation != null) {
                formatter.node(explanation);
            }
            return new WorkValidationException(formatter.toString(), ImmutableList.copyOf(problems));
        }
    }
}

@@ -1036,44 +1036,8 @@
 st;%0A
-import java.util.function.Function;%0A
 impo
@@ -2575,33 +2575,24 @@
     
-ValidationErrorS
+String s
 ummar
-izer
+y =
  sum
@@ -2601,41 +2601,17 @@
 rize
-r = new ValidationErrorSummarizer
+InContext
 (val
@@ -2710,28 +2710,9 @@
 mmar
-izer.apply(problems)
+y
 );%0A 
@@ -2995,58 +2995,15 @@
     
-/**%0A         * This function can build a format
+priva
 te
-d
  Str
@@ -3018,608 +3018,90 @@
 ariz
-ing a list of problems.%0A         */%0A        public static final class ValidationErrorSummarizer implements Function%3CList%3CString%3E, String%3E %7B%0A            private final String validatedObjectName;%0A            private final WorkValidationContext validationContext;%0A%0A            public ValidationErrorSummarizer(String validatedObjectName, WorkValidationContext validationContext) %7B%0A                this.validatedObjectName = validatedObjectName;%0A                this.validationContext = validationContext;%0A            %7D%0A%0A            @Override%0A            public String apply(List%3CString%3E problems) %7B%0A    
+eInContext(String validatedObjectName, WorkValidationContext validationContext) %7B%0A
     
@@ -3196,20 +3196,16 @@
         
-  
-  
 problems
@@ -3279,20 +3279,16 @@
         
-    
 validate
@@ -3300,20 +3300,16 @@
 ctName,%0A
-    
         
@@ -3386,35 +3386,27 @@
 ));%0A        
-    %7D%0A%0A    
+%7D%0A%0A
         priv
@@ -3484,28 +3484,24 @@
             
- 
-   
 return types
@@ -3513,20 +3513,16 @@
 () == 1%0A
-    
         
@@ -3596,20 +3596,16 @@
 ) + %22'%22%0A
-    
         
@@ -3722,35 +3722,27 @@
 '%22;%0A        
-    %7D%0A%0A    
+%7D%0A%0A
         priv
@@ -3862,26 +3862,16 @@
       %7D%0A
-        %7D%0A
     %7D%0A%0A 

Simplify exception summarization by removing inner class