package jp.sourceforge.cfneo.at4ie2.csvimpl;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import jp.sourceforge.cfneo.at4ie2.BTRuntimeError;
import jp.sourceforge.cfneo.at4ie2.api.test.Context;
import jp.sourceforge.cfneo.at4ie2.api.test.TestCase;
import jp.sourceforge.cfneo.at4ie2.api.test.TestCaseList;
import jp.sourceforge.cfneo.at4ie2.api.test.TestRunner;
import jp.sourceforge.cfneo.at4ie2.api.test.impl.DefaultContext;
import jp.sourceforge.cfneo.at4ie2.api.test.impl.DefaultTestCaseList;
import jp.sourceforge.cfneo.at4ie2.utils.TestUtil;

import org.apache.log4j.Logger;

public class CsvTestRunner implements TestRunner {

	Logger logger = Logger.getLogger(CsvTestRunner.class);
	Context context;
	TestCaseList testCaseList;

	public CsvTestRunner(Context context, String filepath) {
		this.context = context;
		this.testCaseList = new DefaultTestCaseList(CsvContext.getInstance());
		try {
			BufferedReader br = new BufferedReader(new FileReader(filepath));
			String line = null;
			int id = 0;
			while ((line = br.readLine()) != null) {
				id++;
				TestUtil.appendTestCase(context, testCaseList, id, line);
			}
			br.close();
		} catch (FileNotFoundException e) {
			throw new BTRuntimeError(e);
		} catch (IOException e) {
			throw new BTRuntimeError(e);
		}
	}

	@Override
	public void run() {
		try {
			DefaultContext.getInstance().getResultLogger().resetLog();
			for (int row = 0; row < this.testCaseList.size(); row++) {
				TestCase testCase = this.testCaseList.getTestCase(row);
				logger.debug(testCase);
				if (this.context.isToolTest() == false) {
					testCase.doTest();
				}
			}
		} catch (BTRuntimeError e) {
			DefaultContext.getInstance().getResultLogger().writeResult(e.getMessage());
			throw e;
		} finally {
			logger.info("******************************");
			logger.info("***** Result log - start *****");
			logger.info(DefaultContext.getInstance().getResultLogger().readResult());
			logger.info("***** Result log - end   *****");
			logger.info("******************************");
		}
	}

}
