package jp.ac.nii.icpc2010.recorder;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import jp.ac.nii.icpc2010.TronException;
import jp.ac.nii.icpc2010.manager.OptionsManager;

/**
 * A file-based recorder implementation. Not threadsafe. 
 * @author johan
 *
 */
public class FileRecorder extends AbstractRecorder {

	private String _fileName;
	
	public FileRecorder(String[] playerNames, String fileName, OptionsManager om) {
		super(playerNames, om);
		_fileName = fileName;
	}
	
	public void closeWriting() throws TronException {
		super.closeWriting();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(_fileName));
			if (!om.isTournamentMode())
				System.out.println("writing to " + _fileName);
			oos.writeObject(getEvents());
			oos.writeObject(getPlayerNames());
			oos.writeObject(getPlayerScores());
			oos.close();
		
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw new TronException("Unable to save log to file.");
		}
			
	}
	
	@SuppressWarnings("unchecked")
	public void load() throws TronException {
		super.load();
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(_fileName));
			setEvents((List<PlayerEvent[]>) ois.readObject());
			setPlayerNames((String[]) ois.readObject());
			setPlayerScores((List<Double>) ois.readObject());
			ois.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw new TronException("Unable to read log from file.");
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
			throw new TronException("Unable to read log from file.");
		}
		
		
	}
	
	
}
