/* This tool will read JPEG comments from files under the image directory and stuff them into a comments.properties file */

import se.datadosen.jalbum.*;
import se.datadosen.util.IO;

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

JProgressDialog progress = new JProgressDialog(window, "Add JPEG comments", false);

void processFile(Map comments, File f) {
	String existing = (String)comments.get(f.getName());
	if (existing == null || existing.length() == 0) addOldJPEGComment(f, comments);
}

void processDir(File dir) {
	File[] files = engine.listFiles(dir, true, rootOutputDirectory);
	File commentsFile = new File(dir, "comments.properties");
	Map comments;
	if (commentsFile.exists()) comments = IO.readMapFile(commentsFile);
	else comments = new HashMap();
	
	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(comments, f);
			}
			catch (Exception ex) {
				System.err.println(ex);
				nErrors++;
				lastException = ex;
				errorFile = f;
			}
			progress.imageProcessingFinished(eventObject);
			if (eventObject.isAborted()) throw new OperationAbortedException("");
			nProcessed++;
		}
	}
	IO.writeMapFile(comments, commentsFile);
}


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

}

void addOldJPEGComment(File file, Map vars) {
  try {
	 marcoschmidt.ImageInfo ii = getImageInfo(file);

	 // Add comments from marcoschmidt.ImageInfo if exists instead of EXIF comment
	 String comment = ""; //$NON-NLS-1$
	 int ncomm = ii.getNumberOfComments();
	 for (int i = 0; i < ncomm; i++) {
		if (i > 0) {
		   comment += ", "; //$NON-NLS-1$
		}
		comment += ii.getComment(i);
	 }
	 comment = comment.trim();
	 if (comment.length() > 0 && !isCopyright(comment)) {
		vars.put(file.getName(), comment); // Replace EXIF comment //$NON-NLS-1$
	 }
  }
  catch (Throwable t) {
	 t.printStackTrace(System.err);
  }
}

boolean isCopyright(String s) {
  if (s.startsWith("ACD Systems Digital Imaging") || //$NON-NLS-1$
	  s.startsWith("LEAD Technologies") || //$NON-NLS-1$
	  s.startsWith("AppleMark") || //$NON-NLS-1$
	  s.startsWith("Intel(R) JPEG Library") || //$NON-NLS-1$
	  s.startsWith("Created with The GIMP") || //$NON-NLS-1$
	  s.startsWith("ASCII") || //$NON-NLS-1$
	  s.startsWith("OLYMPUS DIGITAL CAMERA") || //$NON-NLS-1$
	  s.startsWith("File written by Adobe Photoshop")) { //$NON-NLS-1$
	 return true;
  }
  return false;
}


marcoschmidt.ImageInfo getImageInfo(File file) throws IOException {
  marcoschmidt.ImageInfo ii = new marcoschmidt.ImageInfo();
  FileInputStream fis = new FileInputStream(file);
  ii.setCollectComments(true);
  ii.setInput(fis);
  ii.setEncoding(engine.getTextEncoding());
  if (!ii.check()) {
	 throw new IOException(Msg.getString(
		 "engine.unsupportedFileFormatError") + //$NON-NLS-1$
						   file.getName());
  }
  fis.close();
  return ii;
}



// Execution starts here

msg =
"This tool will read JPEG comments from files under the image directory and add missing comments to the comments.properties file";
int option = JOptionPane.showConfirmDialog(window, msg, "", 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);
