/* Server mode tool */

import se.datadosen.component.*;
import se.datadosen.io.ConsoleStream;
import se.datadosen.util.IO;

int SLEEP_TIME = 5000; // milliseconds to sleep before each file system poll

PrintStream log = System.out;
boolean running = true;

// It seems that we have to declare classes in global scope with Java 1.5
WindowListener wl = new WindowAdapter() {
	public void windowClosing(WindowEvent e) {
      	running = false;
	}
};

msg =
"This tool makes JAlbum monitor changes under the image directory and trigger automatic\n" +
"album updates. As soon as a file is added, updated or removed under the image directory,\n" +
"a Make album operation is triggered. Then JAlbum returns to again monitor changes.\n" +
"(This tool can preferrably run from the command line on a server)\n\n" +
"Note, for proper operation, the output directory must NOT be under the image directory,\n" +
"otherwise an infinite album building loop will occur!\n" +
"To exit server mode, just close the server mode window";

if (window != null) {   
      JDialog console = new JDialog(window, "Server mode", false);
      console.addWindowListener(wl);
	
      JScrollPane sp = new JScrollPane();
      JTextArea ta = new JSmartTextArea();
      ta.setEditable(false);
      sp.getViewport().add(ta, null);
      log = new PrintStream(new ConsoleStream(ta), true);
      
      Container c = console.getContentPane();
      c.setLayout(new BorderLayout());
      c.add(sp, BorderLayout.CENTER);
      console.setSize(new Dimension(460,200));
      console.validate();
	JOptionPane.showMessageDialog(window, msg, "About server mode", JOptionPane.INFORMATION_MESSAGE);
      console.setVisible(true);
}


long lastModified = IO.deepLastModified(rootImageDirectory);

log.println("Monitoring directory " + rootImageDirectory.getName() + "...");
while (running) {
	Thread.currentThread().sleep(SLEEP_TIME);
	long newLastModified = IO.deepLastModified(rootImageDirectory);
	if (newLastModified > lastModified) {
		log.println("Detected file system change. Making album at " + new Date() + "...");
		lastModified = newLastModified;
		if (window != null) window.doMakeAlbum();
		else engine.makeAlbum();
		log.println("Done");
		log.println("Monitoring directory " + rootImageDirectory.getName() + "...");
	}
}
System.out.println("Exiting server mode");

