package jp.sourceforge.cfneo.at4ie2.api.test.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import jp.sourceforge.cfneo.at4ie2.BTRuntimeError;
import jp.sourceforge.cfneo.at4ie2.api.test.BTAssertException;
import jp.sourceforge.cfneo.at4ie2.api.test.ResultLogger;

public class DefaultResultLogger implements ResultLogger {

	static DefaultResultLogger _instance;

	public static DefaultResultLogger getInstance() {
		if (_instance == null) {
			_instance = new DefaultResultLogger();
		}
		return _instance;
	}

	String logFilePath;

	DefaultResultLogger() {
		this.logFilePath = DefaultContext.getInstance().getLogFile();
	}

	@Override
	public void resetLog() {
		try {
			File f = new File(this.logFilePath);
			f.delete();
			f.createNewFile();
		} catch (IOException e) {
			throw new BTRuntimeError(e);
		}
	}
	@Override
	public String readResult() {
		try {
			BufferedReader br = new BufferedReader(new FileReader(this.logFilePath));
			StringBuilder sb = new StringBuilder();
			String line = null;
			int row = 0;
			while ((line = br.readLine()) != null) {
				row++;
				sb.append("[");
				sb.append(row);
				sb.append("]:");
				sb.append(line);
			}
			br.close();
			return sb.toString();
		} catch (Exception e) {
			throw new BTRuntimeError(e);
		}
	}
	@Override
	public void writeResult(String logginString) {
		try {
			PrintWriter pw = new PrintWriter(new FileWriter(this.logFilePath, true));
			pw.println(logginString);
			pw.close();
		} catch (IOException e1) {
			throw new BTRuntimeError(e1);
		}
	}
	@Override
	public void writeResult(BTAssertException e) {
		this.writeResult(e.getMessage());
	}

}
