package org.builditbreakit.seada.logappend;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.builditbreakit.seada.common.data.GalleryState;
import org.builditbreakit.seada.common.io.LogFileReader;
import org.builditbreakit.seada.logappend.io.LogFileWriter;

public class GalleryUpdateManager {
	
	private Map<String, GalleryUpdate> states = new HashMap<String, GalleryUpdate>();
	
	/**
	 * Find the existing gallery state for a particular path -- or create a new one, if
	 * the path doesn't exist yet. This allows the same state to be reused without being
	 * read/written between each use.
	 */
	public GalleryUpdate getGalleryFor(AppendCommand cmd) throws IOException, SecurityException {
		File f = new File(cmd.getLogfile());
		String password = cmd.getToken();
		// Convert to canonical version of path so different paths to the same logfile
		// are resolved to the same thing.
		String key = f.getCanonicalPath();
		GalleryUpdate item = states.get(key);
		if (item == null) {
			GalleryState state;
			if (f.exists()) {
				LogFileReader reader = new LogFileReader(new File(key));
				state = reader.read(password);
			} else {
				state = new GalleryState();
			}
			item = new GalleryUpdate(state, f, password);
			states.put(key, item);
		} else if (!item.password.equals(password)) {
			throw new IllegalArgumentException("Can't change password now.");
		}
		return item;
	}
	
	public boolean save() {
		boolean ok = true;
		for (GalleryUpdate item : states.values()) {
			if (item.modified) {
				try {
					LogFileWriter writer = new LogFileWriter(item.path);
					writer.write(item.state, item.password);
				} catch (IOException e) {
					System.out.println("invalid");
					ok = false;
				}
			}
		}
		return ok;
	}
	
}

@@ -134,16 +134,80 @@
 til.Map;
+%0Aimport java.util.regex.Matcher;%0Aimport java.util.regex.Pattern;
 %0A%0Aimport
@@ -499,16 +499,86 @@
 e%3E();%0A%09%0A
+%09private static final Pattern cantBeFile = Pattern.compile(%22.*/$%22);%0A%09%0A
 %09/**%0A%09 *
@@ -886,42 +886,165 @@
 %7B%0A%09%09
-File f = new File(cmd.getLogfile()
+String lf = cmd.getLogfile();%0A%09%09Matcher m = cantBeFile.matcher(lf);%0A%09%09if (m.matches()) %7B%0A%09%09%09throw new IOException(%22Bad logfile.%22);%0A%09%09%7D%0A%09%09File f = new File(lf
 );%0A%09

fix issue where we truncate trailing slash in log filename