/*
 * WatchLogFrame.java
 *
 * Created on 16. Dezember 2008, 08:36
 */

package watchlog;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import name.pachler.nio.file.WatchService;
import name.pachler.nio.file.ClosedWatchServiceException;
import name.pachler.nio.file.FileSystems;
import name.pachler.nio.file.Path;
import name.pachler.nio.file.Paths;
import name.pachler.nio.file.StandardWatchEventKind;
import name.pachler.nio.file.WatchEvent;
import name.pachler.nio.file.WatchKey;
import name.pachler.nio.file.ext.Bootstrapper;

/**
 *
 * @author  count
 */
public class WatchLogFrame extends javax.swing.JFrame {
	private WatchService service;
	private WatchKey currentWatch;
	private Path currentWatchPath;
	private LogTableModel logTableModel = new LogTableModel();
	private Thread fileWatchThread = new Thread(){
		@Override
		public void run(){
			try {
				for(;;)
				{
					WatchKey key = service.take();
					List<WatchEvent<?>> eventList = key.pollEvents();

					key.reset();
					WatchEventDispatcher wed = new WatchEventDispatcher(eventList);
					SwingUtilities.invokeLater(wed);
				}
			} catch(ClosedWatchServiceException cwsx){
				return;
			} catch (InterruptedException ex) {
				return;
			}
		}
	};

	private class WatchEventDispatcher implements Runnable {
		private List<WatchEvent<?>> eventList;
		WatchEventDispatcher(List<WatchEvent<?>> eventList){
			this.eventList = eventList;
		}
		public void run(){
			for(WatchEvent<?> event : eventList){
				WatchEvent.Kind<?> kind = event.kind();
				try {
					WatchEvent<Path> pathWatchEvent = (WatchEvent<Path>)event;
					Path path = pathWatchEvent.context();
					File file = Bootstrapper.pathToFile(path);
					long time = System.currentTimeMillis();
					if(kind == StandardWatchEventKind.ENTRY_CREATE){
						logTableModel.addRecord(time, LogTableModel.CREATED, file);
					} else if(kind == StandardWatchEventKind.ENTRY_DELETE){
						logTableModel.addRecord(time, LogTableModel.DELETED, file);
					} else if(kind == StandardWatchEventKind.ENTRY_MODIFY){
						logTableModel.addRecord(time, LogTableModel.MODIFIED, file);
					}
				} catch(ClassCastException ccx){
					// ignore other WatchEvent types
				}
			}
		}
	}
    /** Creates new form WatchLogFrame */
    public WatchLogFrame() {
        initComponents();
		watchLogTable.setModel(logTableModel);
		service = FileSystems.getDefault().newWatchService();
		fileWatchThread.start();
    }

	private WatchKey getCurrentWatch() {
		return currentWatch;
	}


	private void setCurrentWatch(File selectedFile) throws IOException {
		if(currentWatch != null)
		{
			currentWatch.cancel();
			currentWatch = null;
			currentWatchPath = null;
		}
		currentWatch = null;
		watchPathTextField.setText("");
		watchLogTable.setEnabled(false);
		
		Path path = null;
		if(selectedFile != null){
			path = Paths.get(selectedFile.toString());

			currentWatch = path.register(service, StandardWatchEventKind.ENTRY_CREATE, StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);
		}
		if(currentWatch != null){
			watchPathTextField.setText(selectedFile.toString());
			logTableModel.clear();
			currentWatchPath = path;
		}
		watchLogTable.setEnabled(currentWatch != null);
	}
	
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        watchLogTable = new javax.swing.JTable();
        panel1 = new java.awt.Panel();
        watchPathTextField = new javax.swing.JTextField();
        setWatchButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        watchLogTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        watchLogTable.setEnabled(false);
        jScrollPane1.setViewportView(watchLogTable);

        watchPathTextField.setEditable(false);
        watchPathTextField.setText("jTextField1");

        setWatchButton.setText("Set Watch...");
        setWatchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setWatchButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addComponent(setWatchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(watchPathTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE))
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(setWatchButton)
                .addComponent(watchPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Dialog", 0, 12));
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setText("This example allows you to watch a specific directory. Create a watch by clicking 'Set Watch...' and choose a directory. Copy/move files into and out of this directory or rename files withing it with your platform's file manager (on Windows, that's Explorer).");
        jTextArea1.setWrapStyleWord(true);
        jTextArea1.setBorder(null);
        jTextArea1.setOpaque(false);
        jScrollPane2.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
                    .addComponent(panel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void setWatchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setWatchButtonActionPerformed

	JFileChooser chooser = new JFileChooser();
	chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
	if(getCurrentWatchPath() != null)
		chooser.setCurrentDirectory(Bootstrapper.pathToFile(getCurrentWatchPath()));
	int result = chooser.showOpenDialog(this);
	if(result == JFileChooser.APPROVE_OPTION){
			try {
				setCurrentWatch(chooser.getSelectedFile());
			} catch (IOException ex) {
				JOptionPane.showMessageDialog(this, "Cannot watch selected file, try another one", "Error", JOptionPane.ERROR_MESSAGE);
			}
	}
}//GEN-LAST:event_setWatchButtonActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
		try {
			service.close();
			try {
				fileWatchThread.join();
			} catch (InterruptedException ex) {
				Logger.getLogger(WatchLogFrame.class.getName()).log(Level.SEVERE, null, ex);
			}
		} catch (IOException ex) {
			Logger.getLogger(WatchLogFrame.class.getName()).log(Level.SEVERE, null, ex);
		}
}//GEN-LAST:event_formWindowClosed

 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private java.awt.Panel panel1;
    private javax.swing.JButton setWatchButton;
    private javax.swing.JTable watchLogTable;
    private javax.swing.JTextField watchPathTextField;
    // End of variables declaration//GEN-END:variables

	private Path getCurrentWatchPath() {
		return currentWatchPath;
	}

}
