/*
 * Copyright 2020 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.watch.registry.impl;

import net.rubygrapefruit.platform.file.FileWatcher;
import org.gradle.internal.snapshot.FileSystemLocationSnapshot;
import org.gradle.internal.snapshot.SnapshotHierarchy;
import org.gradle.internal.watch.registry.FileWatcherUpdater;
import org.gradle.internal.watch.vfs.WatchMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Updater for hierarchical file watchers.
 *
 * For hierarchical watchers, we can use the registered watchable hierarchies as watched directories.
 * Build root directories are always watchable hierarchies.
 * Watching the build root directories is better since they are less likely to be deleted and
 * nearly no changes to the watched directories are necessary when running builds on the same project.
 *
 * To allow deleting the build root directories, we need to stop watching a build root directory if there are no more snapshots in the VFS inside,
 * since watched directories can't be deleted on Windows.
 *
 * The build root directories are discovered as included builds are encountered at the start of a build, and then they are removed when the build finishes.
 *
 * This is the lifecycle for the watchable hierarchies:
 * - During a build, there will be various calls to {@link FileWatcherUpdater#registerWatchableHierarchy(File, File, SnapshotHierarchy)},
 *   each call augmenting the collection. The watchers will be updated accordingly.
 * - When updating the watches, we watch watchable hierarchies registered for this build or old watched directories from previous builds instead of
 *   directories inside them.
 * - At the end of the build
 *   - stop watching the watchable directories with nothing to watch inside
 *   - remember the currently watched directories as old watched directories for the next build
 *   - remove everything that isn't watched from the virtual file system.
 */
public class HierarchicalFileWatcherUpdater extends AbstractFileWatcherUpdater {
    private static final Logger LOGGER = LoggerFactory.getLogger(HierarchicalFileWatcherUpdater.class);

    private final FileSystemLocationToWatchValidator locationToWatchValidator;
    private final MovedHierarchyHandler movedHierarchyHandler;
    private WatchedHierarchies watchedHierarchies = WatchedHierarchies.EMPTY;

    public HierarchicalFileWatcherUpdater(
        FileWatcher fileWatcher,
        FileSystemLocationToWatchValidator locationToWatchValidator,
        WatchableHierarchies watchableHierarchies,
        MovedHierarchyHandler movedHierarchyHandler
    ) {
        super(fileWatcher, watchableHierarchies);
        this.locationToWatchValidator = locationToWatchValidator;
        this.movedHierarchyHandler = movedHierarchyHandler;
    }

    @Override
    public void virtualFileSystemContentsChanged(Collection<FileSystemLocationSnapshot> removedSnapshots, Collection<FileSystemLocationSnapshot> addedSnapshots, SnapshotHierarchy root) {
        boolean directoriesToWatchChanged = watchableHierarchies.getRecentlyUsedHierarchies().stream().anyMatch(watchableHierarchy -> {
            boolean hasSnapshotsToWatch = root.hasDescendantsUnder(watchableHierarchy.toString());
            if (watchedHierarchies.contains(watchableHierarchy)) {
                // Need to stop watching this hierarchy
                return !hasSnapshotsToWatch;
            } else {
                // Need to start watching this hierarchy
                return hasSnapshotsToWatch;
            }
        });
        if (directoriesToWatchChanged) {
            updateWatchedHierarchies(root);
        }
    }

    @Override
    public void registerWatchableHierarchy(File watchableHierarchy, File probeFile, SnapshotHierarchy root) {
        watchableHierarchies.registerWatchableHierarchy(watchableHierarchy, probeFile, root);
        updateWatchedHierarchies(root);
    }

    @Override
    protected SnapshotHierarchy doUpdateVfsOnBuildStarted(SnapshotHierarchy root) {
        SnapshotHierarchy newRoot = movedHierarchyHandler.handleMovedHierarchies(root);
        if (newRoot != root) {
            updateWatchedHierarchies(newRoot);
        }
        return newRoot;
    }

    @Override
    public SnapshotHierarchy updateVfsOnBuildFinished(SnapshotHierarchy root, WatchMode watchMode, int maximumNumberOfWatchedHierarchies) {
        SnapshotHierarchy newRoot = watchableHierarchies.removeUnwatchableContent(
            root,
            watchMode,
            watchedHierarchies::contains,
            maximumNumberOfWatchedHierarchies,
            createInvalidator()
        );

        updateWatchedHierarchies(newRoot);
        LOGGER.info("Watched directory hierarchies: {}", watchedHierarchies.getWatchedRoots());
        return newRoot;
    }

    @Override
    public Collection<File> getWatchedRoots() {
        return watchedHierarchies.getWatchedRoots();
    }

    private void updateWatchedHierarchies(SnapshotHierarchy root) {
        Set<File> oldWatchedRoots = watchedHierarchies.getWatchedRoots();
        watchedHierarchies = WatchedHierarchies.resolveWatchedHierarchies(watchableHierarchies, root);
        Set<File> newWatchedRoots = watchedHierarchies.getWatchedRoots();

        if (newWatchedRoots.isEmpty()) {
            LOGGER.info("Not watching anything anymore");
        }
        Set<File> hierarchiesToStopWatching = new HashSet<>(oldWatchedRoots);
        Set<File> hierarchiesToStartWatching = new HashSet<>(newWatchedRoots);
        hierarchiesToStopWatching.removeAll(newWatchedRoots);
        hierarchiesToStartWatching.removeAll(oldWatchedRoots);
        if (hierarchiesToStartWatching.isEmpty() && hierarchiesToStopWatching.isEmpty()) {
            return;
        }
        if (!hierarchiesToStopWatching.isEmpty()) {
            fileWatcher.stopWatching(hierarchiesToStopWatching);
        }
        if (!hierarchiesToStartWatching.isEmpty()) {
            fileWatcher.startWatching(hierarchiesToStartWatching.stream()
                .peek(locationToWatchValidator::validateLocationToWatch)
                .peek(watchableHierarchies::armWatchProbe)
                .collect(Collectors.toList())
            );
        }
        LOGGER.info("Watching {} directory hierarchies to track changes", newWatchedRoots.size());
    }

    @Override
    protected WatchableHierarchies.Invalidator createInvalidator() {
        return (location, currentRoot) -> currentRoot.invalidate(location, SnapshotHierarchy.NodeDiffListener.NOOP);
    }

    public interface FileSystemLocationToWatchValidator {
        FileSystemLocationToWatchValidator NO_VALIDATION = location -> {};

        void validateLocationToWatch(File location);
    }

    public interface MovedHierarchyHandler {
        /**
         * On Windows when watched hierarchies are moved, the OS does not send a notification,
         * even though the VFS should be updated. Our best bet here is to cull any moved watch
         * roots from the VFS at the start of every build.
         */
        SnapshotHierarchy handleMovedHierarchies(SnapshotHierarchy root);
    }
}

@@ -1101,44 +1101,8 @@
 Set;
-%0Aimport java.util.stream.Collectors;
 %0A%0A/*
@@ -6614,34 +6614,8 @@
     
-fileWatcher.startWatching(
 hier
@@ -6641,38 +6641,15 @@
 ing.
-stream()%0A                .peek
+forEach
 (loc
@@ -6695,16 +6695,17 @@
 ToWatch)
+;
 %0A       
@@ -6713,17 +6713,42 @@
     
-    .peek
+hierarchiesToStartWatching.forEach
 (wat
@@ -6780,16 +6780,17 @@
 chProbe)
+;
 %0A       
@@ -6798,54 +6798,60 @@
     
-    .collect(Collectors.toList())%0A            
+fileWatcher.startWatching(hierarchiesToStartWatching
 );%0A 

Simplify watch starting