package com.mycompany;

import java.io.IOException;
import java.nio.file.*;
import java.util.Scanner;

import static java.nio.file.StandardWatchEventKinds.*;

public class App {
    public static void main(String[] args) throws IOException, InterruptedException {
        WatchService watcher = FileSystems.getDefault().newWatchService();
        Path path = FileSystems.getDefault().getPath("/home", "vpupkin");
        System.out.println(path.toString());
        WatchKey key =
                path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        Thread t = new Thread(() -> {
            do {
                WatchKey watchKey = null;
                try {
                    watchKey = watcher.take();
                } catch (InterruptedException e) {
                    return;
                }
                for (WatchEvent<?> event : watchKey.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    if (kind == OVERFLOW) {
                        continue;
                    }
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    Path child = path.resolve(filename);
                    String contentType = null;
                    try {
                        contentType = Files.probeContentType(child);
                    } catch (IOException e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == contentType) {
                        System.out.println("Null");
                        continue;
                    }
                    if (!contentType.equals("text/plain")) {
                        System.err.format("New file '%s'" +
                                " is not a plain text file.%n", filename);
                        continue;
                    }
                    System.out.format("Emailing file %s%n", filename);
                }
                boolean valid = key.reset();
                if (!valid) {
                    return;
                }
            } while (true);
        });
        t.start();
        Scanner sc = new Scanner(System.in);
        String next;
        do {
            next = sc.next();
        } while (!next.equals("stop"));
        t.interrupt();
        System.out.println("Bye!");
    }
}
