package edu.calpoly.csc480.Entomo.Seer;

import java.io.*;
import java.util.*;

import com.bcurry.www.text.*;
import com.bcurry.www.util.*;

import edu.calpoly.csc480.Entomo.Area.*;
import edu.calpoly.csc480.Entomo.Main.*;

public class LogView
{
	static protected String headBanner = "\n";
	static protected String footBanner = "\n" +
	 "________________________________________" +
	 "________________________________________" + "\n"
	;
	
	public LogView() {
		formater = new DateFormater();
		
		try {
			setFilename(formater.formatFilename(new Date()) + ".log");
		} catch (IOException err) {err.printStackTrace();}
	}
	
	final public String getFilename()			{return file.getAbsolutePath();}
	
	public void setOwner(SeerView view) {
		this.view = view;
	}

	public void setDocument(Seer seer) {
		this.seer = seer;
		this.almanac = seer.getArea().getAlmanac();
	}
	
	public void setFilename(String fileName) throws IOException {
		file = new BasicFile(fileName);
		new FileOutputStream(file);
	}

	public void start() {
		final boolean autoFlush = true;
		
		try {
			fileStream = new FileOutputStream(file);
		} catch (IOException err) {err.printStackTrace();}

		textWriter = new PrintWriter(
		 new OutputStreamWriter(fileStream), autoFlush);
		
		textWriter.print(HelpMenu.getAboutText() + "\n\n");
		textWriter.print(
		 headBanner + "foundation" + footBanner +
		 "inital time:   " + formater.formatTimestamp(new Date()) + "\n" +
		 "free memory:   " + Runtime.getRuntime().freeMemory() + "\n" +
		 "area filename: " + seer.getArea().getName() + "\n" +
		 "area layout:\n"
		);

		try {
			seer.getArea().write(textWriter);
		} catch (IOException err) {err.printStackTrace();}
	}
	
	public void next() {
		if (fileStream == null || textWriter == null) {
			start();
		}

		textWriter.print(
		 headBanner + "cycle " + seer.getCycle() + footBanner
		);
		
		textWriter.print(
		 "Ants Remaining: " + almanac.antsLeft + "\n" + 
		 "Ants Perished: "  + almanac.antsGone + "\n" +
		 "Food Remaining: " + almanac.foodLeft + "\n" +
		 "Food Collected: " + almanac.foodGone + "\n"
		);
	}
	
	public void stop() {
		if (fileStream != null && textWriter != null) {
			textWriter.print(
			 headBanner + "completion" + footBanner +
			 "ending time: " + formater.formatTimestamp(new Date()) + "\n"
			);
			
			try {
				fileStream.close();
			} catch(IOException err) {err.printStackTrace();}
		}

		fileStream = null;
		textWriter = null;
	}

	protected Seer seer;
	protected SeerView view;
	protected Almanac almanac;
	
	protected DateFormater formater;
	protected BasicFile file;
	
	protected OutputStream fileStream;
	protected PrintWriter textWriter;
}