/*
 * 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.caching.internal.tasks;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.hash.HashCode;
import org.gradle.api.internal.changedetection.state.TypeImplementation;
import org.gradle.caching.internal.BuildCacheHasher;
import org.gradle.caching.internal.DefaultBuildCacheHasher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.List;

public class DefaultTaskOutputCachingBuildCacheKeyBuilder {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTaskOutputCachingBuildCacheKeyBuilder.class);

    public static final TaskOutputCachingBuildCacheKey NO_CACHE_KEY = new DefaultTaskOutputCachingBuildCacheKeyBuilder().build();

    private BuildCacheHasher hasher = new DefaultBuildCacheHasher();
    private String taskClass;
    private HashCode classLoaderHash;
    private List<HashCode> actionsClassLoaderHashes;
    private List<String> actionsTypes;
    private final ImmutableSortedMap.Builder<String, HashCode> inputHashes = ImmutableSortedMap.naturalOrder();
    private final ImmutableSortedSet.Builder<String> outputPropertyNames = ImmutableSortedSet.naturalOrder();

    public DefaultTaskOutputCachingBuildCacheKeyBuilder appendTaskImplementation(TypeImplementation taskImplementation) {
        this.taskClass = taskImplementation.getTypeName();
        hasher.putString(taskClass);
        log("taskClass", taskClass);

        HashCode hashCode = taskImplementation.getClassLoaderHash();
        this.classLoaderHash = hashCode;
        if (hashCode != null) {
            hasher.putHash(hashCode);
        }
        log("classLoaderHash", hashCode);
        return this;
    }

    public DefaultTaskOutputCachingBuildCacheKeyBuilder appendTaskActionImplementations(Collection<TypeImplementation> taskActionImplementations) {
        int actionCount = taskActionImplementations.size();
        List<String> actionsTypes = Lists.newArrayListWithCapacity(actionCount);
        List<HashCode> actionsClassLoaderHashes = Lists.newArrayListWithCapacity(actionCount);
        for (TypeImplementation actionImpl : taskActionImplementations) {
            String actionType = actionImpl.getTypeName();
            actionsTypes.add(actionType);
            hasher.putString(actionType);
            log("actionsType", actionType);

            if (!actionImpl.hasUnknownClassLoader()) {
                HashCode hashCode = actionImpl.getClassLoaderHash();
                hasher.putHash(hashCode);
                log("actionsClassLoaderHash", hashCode);
            }
        }

        this.actionsTypes = actionsTypes;
        this.actionsClassLoaderHashes = actionsClassLoaderHashes;
        return this;
    }

    public DefaultTaskOutputCachingBuildCacheKeyBuilder appendInputPropertyHash(String propertyName, HashCode hashCode) {
        hasher.putString(propertyName);
        hasher.putHash(hashCode);
        inputHashes.put(propertyName, hashCode);
        LOGGER.debug("Appending inputPropertyHash for '{}' to build cache key: {}", propertyName, hashCode);
        return this;
    }

    public DefaultTaskOutputCachingBuildCacheKeyBuilder appendOutputPropertyName(String propertyName) {
        outputPropertyNames.add(propertyName);
        hasher.putString(propertyName);
        log("outputPropertyName", propertyName);
        return this;
    }

    private static void log(String name, Object value) {
        LOGGER.debug("Appending {} to build cache key: {}", name, value);
    }

    public TaskOutputCachingBuildCacheKey build() {
        BuildCacheKeyInputs inputs = new BuildCacheKeyInputs(taskClass, classLoaderHash, actionsClassLoaderHashes, actionsTypes, inputHashes.build(), outputPropertyNames.build());
        if (classLoaderHash == null || actionsClassLoaderHashes.contains(null)) {
            return new DefaultTaskOutputCachingBuildCacheKey(null, inputs);
        }
        return new DefaultTaskOutputCachingBuildCacheKey(hasher.hash(), inputs);
    }

    private static class DefaultTaskOutputCachingBuildCacheKey implements TaskOutputCachingBuildCacheKey {
        private final HashCode hashCode;
        private final BuildCacheKeyInputs inputs;

        private DefaultTaskOutputCachingBuildCacheKey(HashCode hashCode, BuildCacheKeyInputs inputs) {
            this.hashCode = hashCode;
            this.inputs = inputs;
        }

        @Override
        public String getHashCode() {
            return Preconditions.checkNotNull(hashCode, "Cannot determine hash code for invalid build cache key").toString();
        }

        @Override
        public BuildCacheKeyInputs getInputs() {
            return inputs;
        }

        @Override
        public boolean isValid() {
            return hashCode != null;
        }

        @Override
        public String toString() {
            return String.valueOf(hashCode);
        }
    }
}

@@ -2196,24 +2196,87 @@
 askClass);%0A%0A
+        if (!taskImplementation.hasUnknownClassLoader()) %7B%0A    
         Hash
@@ -2336,24 +2336,28 @@
 ();%0A        
+    
 this.classLo
@@ -2381,40 +2381,8 @@
 de;%0A
-        if (hashCode != null) %7B%0A
     
@@ -2415,30 +2415,24 @@
 hCode);%0A    
-    %7D%0A
         log(
@@ -2453,32 +2453,42 @@
 sh%22, hashCode);%0A
+        %7D%0A
         return t
@@ -3140,24 +3140,55 @@
 tionType);%0A%0A
+            HashCode hashCode;%0A
             
@@ -3191,17 +3191,16 @@
     if (
-!
 actionIm
@@ -3241,33 +3241,33 @@
             
-H
+h
 ashCode 
 hashCode = a
@@ -3246,32 +3246,77 @@
        hashCode 
+= null;%0A            %7D else %7B%0A                
 hashCode = actio
@@ -3393,33 +3393,38 @@
             
-    log(%22
+%7D%0A            
 actionsClass
@@ -3425,35 +3425,39 @@
 sClassLoaderHash
-%22, 
+es.add(
 hashCode);%0A     
@@ -3455,33 +3455,72 @@
 e);%0A            
-%7D
+log(%22actionsClassLoaderHash%22, hashCode);
 %0A        %7D%0A%0A    

Fix serialization of unknown task classloader more