package com.kodcu.service;

import com.kodcu.other.Item;
import javafx.scene.control.TreeView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.file.*;
import java.util.Objects;
import java.util.function.BiConsumer;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;

/**
 * Created by usta on 31.12.2014.
 */
@Component
public class FileWatchService {

    private final Logger logger = LoggerFactory.getLogger(FileWatchService.class);

    private WatchService watcher = null;
    private Path lastWatchedPath;

    public void registerWatcher(TreeView<Item> treeView, Path path, BiConsumer<TreeView<Item>, Path> browseCallback) {
        try {
            if (Objects.isNull(watcher)) {
                watcher = FileSystems.getDefault().newWatchService();
            }

            if (!path.equals(lastWatchedPath)) {
                if (Objects.nonNull(lastWatchedPath)) {
                    watcher.close();
                    watcher = FileSystems.getDefault().newWatchService();
                }
                lastWatchedPath = path;
                path.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
            }

            WatchKey watckKey = watcher.take();
            watckKey.pollEvents();
            watckKey.reset();
            browseCallback.accept(treeView, path);

        } catch (Exception e) {
            logger.info("Could not register watcher for path: {}", path, e);
        }
    }
}

@@ -211,18 +211,149 @@
 ava.
-nio.file.*
+io.IOException;%0Aimport java.nio.file.FileSystems;%0Aimport java.nio.file.Path;%0Aimport java.nio.file.WatchKey;%0Aimport java.nio.file.WatchService
 ;%0Aim
@@ -792,16 +792,47 @@
 hedPath;
+%0A    private WatchKey watckKey;
 %0A%0A    pu
@@ -1455,25 +1455,21 @@
         
-WatchKey 
+this.
 watckKey
@@ -1548,24 +1548,66 @@
 ey.reset();%0A
+            if (watckKey.isValid()) %7B%0A    
             
@@ -1644,16 +1644,30 @@
 , path);
+%0A            %7D
 %0A%0A      
@@ -1784,11 +1784,237 @@
  %7D%0A    %7D
+%0A%0A    public void invalidate() %7B%0A        if(Objects.nonNull(watcher))%7B%0A            try %7B%0A                watcher.close();%0A            %7D catch (IOException e) %7B%0A                e.printStackTrace();%0A            %7D%0A        %7D%0A    %7D
 %0A%7D%0A

Allow to invalidate filewatcher on-demand