package de.idrinth.waraddonclient.service;

import de.idrinth.waraddonclient.service.logger.BaseLogger;
import de.idrinth.waraddonclient.model.GuiAddonList;
import java.io.File;
import java.io.IOException;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class FileWatcher implements java.lang.Runnable {

    private final GuiAddonList addonList;

    private final WatchService watcher;

    private final BaseLogger logger;
    
    private final Config config;

    public FileWatcher(GuiAddonList addonList, BaseLogger logger, Config config) throws IOException {
        this.addonList = addonList;
        this.logger = logger;
        this.config = config;
        File path = new File(config.getLogsFolder());
        if (!path.exists()) {
            path.mkdirs();
        }
        watcher = path.toPath().getFileSystem().newWatchService();
        WatchEvent.Kind[] modes = new WatchEvent.Kind[2];
        modes[0] = StandardWatchEventKinds.ENTRY_CREATE;
        modes[1] = StandardWatchEventKinds.ENTRY_MODIFY;
        path.toPath().register(watcher, modes);
    }

    @Override
    public void run() {
        try {
            WatchKey key = watcher.take();
            key.pollEvents().stream().filter(this::isValidEvent).map(event -> new File(config.getLogsFolder() + event.context().toString())).filter(this::isValidFile).forEach(file -> addonList.getWatchedFiles().get(file.getName().toLowerCase()).setFileToProcess(file));
            key.reset();
        } catch (InterruptedException ex) {
            logger.error(ex);
        }
    }

    /**
     * is this an event to process?
     *
     * @param event
     * @return
     */
    private boolean isValidEvent(WatchEvent event) {
        return event.kind() == StandardWatchEventKinds.ENTRY_CREATE || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY;
    }

    /**
     * is this a file to process?
     *
     * @param file
     * @return
     */
    private boolean isValidFile(java.io.File file) {
        return addonList.getWatchedFiles().containsKey(file.getName().toLowerCase());
    }
}

@@ -343,16 +343,41 @@
 Service;
+%0Aimport java.util.Arrays;
 %0A%0Apublic
@@ -986,76 +986,108 @@
     
-WatchEvent.Kind%5B%5D modes = new WatchEvent.Kind%5B2%5D;%0A        modes%5B0%5D =
+path.toPath()%0A        .register(%0A            watcher,%0A            Arrays.asList(%0A                   
  Sta
@@ -1123,28 +1123,9 @@
 EATE
-;%0A        modes%5B1%5D =
+,
  Sta
@@ -1153,25 +1153,25 @@
 ENTRY_MODIFY
-;
+)
 %0A        pat
@@ -1171,45 +1171,53 @@
     
-path.toPath().register(watcher, modes
+        .toArray(new WatchEvent.Kind%3C?%3E%5B%5D %7B%7D)
 );%0A 
@@ -1789,32 +1789,32 @@
 @return%0A     */%0A
-
     private bool
@@ -1840,16 +1840,19 @@
 tchEvent
+%3C?%3E
  event) 

Remove raw usage of parameterized class