package edu.wheaton.simulator.statistics;

import java.util.Map;
import java.util.Set;

import com.google.common.collect.ImmutableMap;

import edu.wheaton.simulator.entity.AgentID;

public class Saver {

	private StringBuilder sb;
	
	/**
	 * The table on which all entity snapshots are be stored.
	 */
	private AgentSnapshotTable table;
	
	/**
	 * Map of all PrototypeSnapshots for the simulation
	 * Since PrototypeSnapshots are immutable, this collection is the same for each step
	 */
	private Map<String, PrototypeSnapshot> prototypes; 
	
	/**
	 * Constructor
	 * @param table An AgentSnapshotTable of all AgentSnapshots at every step of the simulation
	 * @param prototypes A Map of PrototypeSnapshots
	 */
	public Saver(AgentSnapshotTable table, Map<String, PrototypeSnapshot> prototypes){
		this.sb = new StringBuilder(); 
		this.table = table; 
		this.prototypes = prototypes; 
	}
	
	/**
	 * Write data serializing the simulation's current state to a file
	 * Saves the state of the most recent completed step only
	 */
	public void save(){
		int currentStep = getCurrentStep();  
		ImmutableMap<AgentID, AgentSnapshot> snaps = table.getSnapshotsAtStep(currentStep); 
		
		//Serialize and write all AgentSnapshots to file
		for(AgentSnapshot snap : snaps.values()){
			sb.append(snap.serialize()); 
		}
		
		//Serialize and write all PrototypeSnapshots to file
		for(PrototypeSnapshot proto : prototypes.values()){
			sb.append(proto.serialize()); 
		}
	}
	
	/**
	 * Get the current step in the simulation
	 * This is assumed to be the highest numbered step stored in the table
	 * @return The current simulation step
	 */
	private int getCurrentStep(){
		Set<Integer> steps = table.getAllSteps();
		int max = 0; 
		
		for(Integer i : steps)
			if(i > max) 
				max = i; 
		
		return max; 
	}
	
}

@@ -1211,24 +1211,125 @@
 tep); %0D%0A%09%09%0D%0A
+%09%09//TODO: Write the dimensions of the grid and other global variables%0D%0A%09%09sb.append(%22Globals%22); %0D%0A%09%09%0D%0A
 %09%09//Serializ
@@ -1340,29 +1340,33 @@
 d write all 
-Agent
+Prototype
 Snapshots to
@@ -1382,45 +1382,99 @@
 for(
-AgentSnapshot snap : snaps.values())%7B
+PrototypeSnapshot proto : prototypes.values())%7B%0D%0A%09%09%09System.out.println(proto.serialize()); 
 %0D%0A%09%09
@@ -1484,20 +1484,21 @@
 .append(
-snap
+proto
 .seriali
@@ -1539,33 +1539,29 @@
 d write all 
-Prototype
+Agent
 Snapshots to
@@ -1577,55 +1577,88 @@
 for(
-PrototypeSnapshot proto : prototypes.values())%7B
+AgentSnapshot snap : snaps.values())%7B%0D%0A%09%09%09System.out.println(snap.serialize()); 
 %0D%0A%09%09
@@ -1660,37 +1660,36 @@
  %0D%0A%09%09%09sb.append(
-proto
+snap
 .serialize()); %0D
@@ -1694,16 +1694,22 @@
  %0D%0A%09%09%7D%0D%0A
+%09%09%0D%0A%0D%0A
 %09%7D%0D%0A%09%0D%0A%09

Work on Saver. Re-arranged saving order so prototypes are saved first. That way they can be used to recreate the Agents when we load