/* JAlbum tool that resets file dates to camera dates */

import se.datadosen.jalbum.*;
import se.datadosen.imaging.exif.*;
import com.drew.metadata.*;
import com.drew.metadata.exif.*;
import com.drew.metadata.iptc.*;
import com.drew.lang.Rational;
import com.drew.imaging.jpeg.*;

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

ProgressDialog progress = new ProgressDialog(null, "Resetting dates", false);

void processFile(File f) {
	try {
		Metadata imageInfo = JpegMetadataReader.readMetadata(f);
		if (imageInfo.containsDirectory(ExifDirectory.class)) {
			Directory dir = imageInfo.getDirectory(ExifDirectory.class);
			String sDate = dir.getString(ExifDirectory.TAG_DATETIME_ORIGINAL);
			Date camerDate = ImageInfoFormatter.parseExifDate(sDate);
			f.setLastModified(camerDate.getTime());
		}
	}
	catch (JpegProcessingException ex) {}	// Just assume this was no JPEG file.
}

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,
			 "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 will reset the file date of all image files under the image directory to the camera (EXIF) date";
int option = JOptionPane.showConfirmDialog(window, msg, "Reset file date to camera date", 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);
