/* JAlbum tool that replaces spaces in filenames with underscores */

import se.datadosen.jalbum.*;

// Global variables
int nProcessed = 0;
int totalFiles = 0;
int nErrors = 0;
Exception lastException = null;
File errorFile = null;

JProgressDialog progress = new JProgressDialog(window, "Replacing spaces with underscores", false);

void processFile(File f) {
	File parentFile = f.getParentFile();
	f.renameTo(new File(parentFile, f.getName().replace(' ', '_')));
}

void processDir(File dir) {
	File[] files = engine.listFiles(dir, true, rootOutputDirectory);
	for (File f : files) {
		if (f.isDirectory()) processDir(f);
		else {
			AlbumBeanEvent eventObject = new AlbumBeanEvent(this, dir,  dir.getName(),
			 "Processing files ", 0, totalFiles, nProcessed+1, totalFiles);
			progress.imageProcessingStarted(eventObject);
			try {
				processFile(f);
			}
			catch (Exception ex) {
				System.err.println(ex);
				nErrors++;
				lastException = ex;
				errorFile = f;
			}
			progress.imageProcessingFinished(eventObject);
			if (eventObject.isAborted()) throw new OperationAbortedException("");
			nProcessed++;
		}
	}
}


void processAlbum() {
	progress.show();
	totalFiles = engine.countFiles(rootImageDirectory);
	processDir(rootImageDirectory);
	//progress.setVisible(false);

}

// Execution starts here

msg =
"This script replaces spaces in filenames of original images with underscores (to ease publishing to some ftp servers)";
int option = JOptionPane.showConfirmDialog(window, msg, "Replace spaces", JOptionPane.OK_OPTION|JOptionPane.CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (option != JOptionPane.YES_OPTION) return;

processAlbum();

if (nErrors > 0)
	JOptionPane.showMessageDialog(window, "" + nErrors + " errors occured during file processing. Last error was: " + lastException + "\nLast file: " + errorFile, "Error report", JOptionPane.WARNING_MESSAGE);
