package br.com.softjava.nuclenfe;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import javax.swing.JOptionPane;

public class MonitorAlteracao {

	private Thread threadMonitor;
	private String dir;

	public static void main(String[] args) {
		new MonitorAlteracao().init();
	}

	private void init() {
		// diretorio onde vai ser feito a verificacao
		setDir("C:/Unimake/UniNFe/10658657000102/Retorno");
		verificaRetornoUninNFe();
	}

	public void verificaRetornoUninNFe() {
		try {
			File file = new File(getDir()+"/51160510658657000102550010000000631000000050-01-eve.xml");
			while (!file.exists()) {
				System.out.println("Aguardando 5 segundos...");
				// Aguarde 5 segundos
				Thread.sleep(5000);
				file = new File("result.xml");
			}
			System.out.println("ok");
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void verificaPasta(String dir) {
		Path path = Paths.get(getDir());
		WatchService watchService = null;
		try {
			watchService = FileSystems.getDefault().newWatchService();
			path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

		} catch (IOException io) {
			io.printStackTrace();
		}
		WatchKey key = null;

		// while (true) {
		try {
			key = watchService.take();

			for (WatchEvent<?> event : key.pollEvents()) {
				Kind<?> kind = event.kind();
				String nomeArquivo = event.context().toString();
				String extensao = nomeArquivo.substring(
						nomeArquivo.lastIndexOf("."), nomeArquivo.length());
				System.out.println("Extensao do arquivo ! " + extensao);
				System.out.println("Extensao do arquivo ! " + nomeArquivo);

				if (nomeArquivo.contains("-sit.xml")) {
					new MontaXMLConsultaNFe().lerXMLRetorno(getDir() + "/"
							+ nomeArquivo);
					// System.out.println("Evento em " + nomeArquivo + " " +
					// kind);
				} else if (nomeArquivo.contains("-sta.xml")) {
					new RetStatusServicoNFe_JAXB().lerXMLRetorno(getDir() + "/"
							+ nomeArquivo);
					// System.out.println("Evento em " + nomeArquivo + " " +
					// kind);
				} else if (nomeArquivo.contains("-num-lot.xml")) {
					threadMonitor.sleep(1000 * 2);
					String numeroLote = new UniNFeNumeroLote()
							.converterXML4Objeto(nomeArquivo);
					JOptionPane.showMessageDialog(null, numeroLote);
					if (nomeArquivo.equals(numeroLote + ".xml")) {
						JOptionPane.showMessageDialog(null, "Igualllll");
						threadMonitor.sleep(1000 * 2);
						new RetEnviNFe_JAXB().lerXMLRetorno(getDir() + "/"
								+ nomeArquivo);
					}
				}

			}
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}

		boolean reset = key.reset();
		if (!reset) {
			// break;
		}
		// }
	}

	public void newFile(String file) {
		System.out.println("evento -> novo arquivo encontrado!! " + file);
	}

//	@Override
//	public void run() {
//		Thread currentThread = Thread.currentThread();
//
//		// thread que fica verificando a pasta
//		while (this.threadMonitor == currentThread) {
//
//			verificaPasta(getDir());
//
//			try {
//				Thread.sleep(1000 * 2); // 2 segundos
//			} catch (InterruptedException e) {
//			}
//		}
//	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public boolean gerouErro(File file) {
		return Boolean.TRUE;
	}

}
