package de.ugoe.cs.eventbench;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import de.ugoe.cs.eventbench.data.IReplayable;
import de.ugoe.cs.eventbench.data.ReplayableEvent;
import de.ugoe.cs.util.StringTools;
import de.ugoe.cs.util.console.Console;

public class ReplayGenerator {
		
	public void createLogfileMultipleSessions(List<List<ReplayableEvent<?>>> sequences, String filename) {
		OutputStreamWriter writer = openReplayFile(filename);
		if( writer!=null ) {		
			try {
				writer.write("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + StringTools.ENDLINE);
				writer.write("<log>" + StringTools.ENDLINE);

				for( List<ReplayableEvent<?>> actions : sequences ) {
					writeSession(actions, writer);
				}
				
				writer.write("</log>" + StringTools.ENDLINE);
				writer.close();
			} catch (IOException e) {
				Console.printerrln("Unable to write replay file " + filename);
			}
		}
	}
	
	public void createLogfileSingleSession(List<ReplayableEvent<?>> actions, String filename) {
		OutputStreamWriter writer = openReplayFile(filename);
		if( writer!=null ) {		
			try {
				writer.write("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + StringTools.ENDLINE);
				writer.write("<log>" + StringTools.ENDLINE);
	
				writeSession(actions, writer);
				
				writer.write("</log>" + StringTools.ENDLINE);
				writer.close();
			} catch (IOException e) {
				Console.printerrln("Unable to write replay file " + filename);
			}
		}
	}

	private OutputStreamWriter openReplayFile(String filename) {
		File file = new File(filename);
		boolean fileCreated;
		try {
			fileCreated = file.createNewFile();
			if( !fileCreated ) {
				Console.traceln("Created logfile " + filename);
			} else {
				Console.traceln("Overwrote existing logfile " + filename);
			}
		} catch (IOException e) {
			Console.printerrln("Unable to create file " + filename);
			Console.printStacktrace(e);
		}
		OutputStreamWriter writer = null;
		try {
			writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-16");
		} catch (IOException e) {
			Console.printerrln("Unable to open file for writing (read-only file):" + filename);
			Console.printStacktrace(e);
		}
		return writer;
	}
	
	private void writeSession(List<ReplayableEvent<?>> actions, OutputStreamWriter writer)
			throws IOException {
		writer.write(" <session>" + StringTools.ENDLINE);
		for( ReplayableEvent<?> currentAction : actions ) {
			
			List<? extends IReplayable> replayables = currentAction.getReplayMessages();
			for( IReplayable replayble : replayables ) {
				writer.write(replayble.getReplayXml()+StringTools.ENDLINE);
			}
		}
		writer.write(" </session>" + StringTools.ENDLINE);
	}

}
