package de.geis.pdfdownloader;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class FileSystemWatcher extends Thread {
	
	public void startWatcher() throws InterruptedException, IOException {
		WatchService watchService = FileSystems.getDefault().newWatchService();		
		WatchKey watchKey = Paths.get(Parameters.getDownloadFolder().toURI()).register(watchService, 
				StandardWatchEventKinds.ENTRY_CREATE);
		
		//Abarbeitung liegen gebliebene Files
		File[] listoffiles = Parameters.getDownloadFolder().listFiles();
		
		for(File file : listoffiles) {
			PropertyDaten propertyDaten = new PropertyDaten(file.getName());
			propertyDaten.run();
		}
		
		//Watcher start
		while(true) {
			watchKey = watchService.take();			
			if (watchKey != null) {
				try {
					TimeUnit.MILLISECONDS.sleep(25);
					for (WatchEvent<?> event : watchKey.pollEvents()) {
						if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
							System.out.println("--- START Sequenz --- " + event.context().toString());
							normalJobPoolExecutor.submit(startSequenz(event));
						}
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			watchKey.reset();
		}
	}

	public static long DELAY = 10L;
	private static ThreadPoolExecutor normalJobPoolExecutor;

	//Erste Sequenz zum Property Laden starten.
	public Runnable startSequenz(WatchEvent<?> event) {
		PropertyDaten propertyDaten = new PropertyDaten(event.context().toString());
		return propertyDaten;
	}

	public FileSystemWatcher() {
		normalJobPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				if (normalJobPoolExecutor != null) {
					normalJobPoolExecutor.shutdown();
				}
			}
		});
	}
	
	@Override
	public void run() {		
		try {
			
			startWatcher();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
