/*
 * Copyright 2015 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.launcher.continuous;

import com.google.common.collect.Lists;
import org.gradle.BuildAdapter;
import org.gradle.BuildResult;
import org.gradle.api.Action;
import org.gradle.api.Task;
import org.gradle.api.Transformer;
import org.gradle.api.execution.TaskExecutionGraph;
import org.gradle.api.execution.TaskExecutionGraphListener;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.FileCollectionInternal;
import org.gradle.api.internal.file.UnionFileCollection;
import org.gradle.api.invocation.Gradle;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.specs.Spec;
import org.gradle.internal.filewatch.FileWatcherEvent;
import org.gradle.internal.filewatch.FileWatcherFactory;
import org.gradle.internal.filewatch.FilteringFileWatcherListener;
import org.gradle.internal.filewatch.StopThenFireFileWatcherListener;
import org.gradle.util.CollectionUtils;

import java.util.Collection;

public class TaskInputsWatcher extends BuildAdapter {
    private final static Logger LOGGER = Logging.getLogger(TaskInputsWatcher.class);
    private final TriggerListener listener;
    private final FileWatcherFactory fileWatcherFactory;
    private final Collection<Task> tasks;

    public TaskInputsWatcher(TriggerListener listener, FileWatcherFactory fileWatcherFactory) {
        this.listener = listener;
        this.fileWatcherFactory = fileWatcherFactory;
        this.tasks = Lists.newLinkedList();
    }

    @Override
    public void buildStarted(Gradle gradle) {
        // Task graph is consumed, so it's empty by the time buildFinished is called
        // Save the list of tasks that will be executed.
        gradle.getTaskGraph().addTaskExecutionGraphListener(new TaskExecutionGraphListener() {
            @Override
            public void graphPopulated(TaskExecutionGraph graph) {
                tasks.addAll(graph.getAllTasks());
            }
        });
    }

    @Override
    public void buildFinished(BuildResult result) {
        final FileCollectionInternal taskInputs = new UnionFileCollection(
            CollectionUtils.collect(tasks, new Transformer<FileCollection, Task>() {
                public FileCollection transform(Task input) {
                    return input.getInputs().getFiles();
                }
            })
        );

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Task inputs: {}", taskInputs.getFiles());
            LOGGER.debug("taskInputs.getFileSystemRoots(): {}", taskInputs.getFileSystemRoots());
        }

        fileWatcherFactory.watch(
            taskInputs.getFileSystemRoots(),
            new Action<Throwable>() {
                @Override
                public void execute(Throwable throwable) {
                    listener.triggered(new DefaultTriggerDetails(TriggerDetails.Type.STOP, "error " + throwable.getMessage()));
                }
            },
            new FilteringFileWatcherListener(
                new Spec<FileWatcherEvent>() {
                    @Override
                    public boolean isSatisfiedBy(FileWatcherEvent element) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("Received file system event: {}", element);
                        }
                        return element.getType().equals(FileWatcherEvent.Type.UNDEFINED)
                            || taskInputs.wouldContain(element.getFile());
                    }
                },
                new StopThenFireFileWatcherListener(new Runnable() {
                    @Override
                    public void run() {
                        listener.triggered(new DefaultTriggerDetails(TriggerDetails.Type.REBUILD, "file change"));
                    }
                })
            )
        );
    }
}

@@ -655,48 +655,8 @@
 s;%0A%0A
-import com.google.common.collect.Lists;%0A
 impo
@@ -798,129 +798,36 @@
 api.
-Transformer;%0Aimport org.gradle.api.execution.TaskExecutionGraph;%0Aimport org.gradle.api.execution.TaskExecutionGraphListen
+execution.TaskExecutionAdapt
 er;%0A
@@ -1390,78 +1390,8 @@
 ner;
-%0Aimport org.gradle.util.CollectionUtils;%0A%0Aimport java.util.Collection;
 %0A%0Apu
@@ -1646,16 +1646,20 @@
 e final 
+File
 Collecti
@@ -1664,19 +1664,26 @@
 tion
-%3CTask%3E task
+Internal taskInput
 s;%0A%0A
@@ -1887,31 +1887,40 @@
 task
-s = Lists.newLinkedList
+Inputs = new UnionFileCollection
 ();%0A
@@ -1990,150 +1990,8 @@
 ) %7B%0A
-        // Task graph is consumed, so it's empty by the time buildFinished is called%0A        // Save the list of tasks that will be executed.%0A
     
@@ -2024,37 +2024,32 @@
 addTaskExecution
-Graph
 Listener(new Tas
@@ -2062,19 +2062,13 @@
 tion
-GraphListen
+Adapt
 er()
@@ -2120,100 +2120,106 @@
 oid 
-graphPopula
+beforeExecu
 te
-d
 (Task
-ExecutionGraph graph) %7B%0A                tasks.addAll(graph.getAllTask
+ task) %7B%0A                FileCollection inputFiles = task.getInputs().getFile
 s()
-)
 ;%0A  
@@ -2232,378 +2232,298 @@
     
-%7D%0A
     
-    %7D);%0A    %7D%0A%0A    @Override%0A    public void buildFinished(BuildResult result) %7B%0A        final FileCollectionInternal taskInputs = new UnionFileCollection(%0A            CollectionUtils.collect(tasks, new Transformer%3CFileCollection, Task%3E() %7B%0A                public FileCollection transform(Task input) %7B%0A                    return input.getInputs().ge
+if(inputFiles instanceof FileCollectionInternal) %7B%0A                    // resolve FileCollection and flatten it if possible%0A                    inputFiles = ((FileCollectionInternal)inputFiles).resolveToFileTreesAndFiles();%0A                %7D%0A                taskInputs.add(inpu
 tFiles
-(
 );%0A
-    
     
@@ -2544,26 +2544,84 @@
     
-    %7D)%0A        );%0A
+%7D);%0A    %7D%0A%0A    @Override%0A    public void buildFinished(BuildResult result) %7B
 %0A   

use resolveToFileTreesAndFiles in TaskInputsWatcher