package jp.sourceforge.cfneo.at4ie2.excelimpl;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import jp.sourceforge.cfneo.at4ie2.BTRuntimeError;
import jp.sourceforge.cfneo.at4ie2.api.test.CommandEnum;
import jp.sourceforge.cfneo.at4ie2.api.test.Context;
import jp.sourceforge.cfneo.at4ie2.api.test.TestCase;
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.DefaultTestCase;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelTestRunner implements TestRunner {

	static final int COMMAND_COLUMN = 0;
	static final int TARGET_COLUMN = 1;
	static final int VALUE_COLUMN = 2;

	Logger logger = Logger.getLogger(ExcelTestRunner.class);
	Context context;
	Workbook book;

	public ExcelTestRunner(Context context, String filepath) {
		this.context = context;
		try {
			this.book = Workbook.getWorkbook(new File(filepath));
		} catch (BiffException e) {
			throw new BTRuntimeError(e);
		} catch (IOException e) {
			throw new BTRuntimeError(e);
		}
	}

	@Override
	public void run() {
		try {
			Sheet[] sheets = this.book.getSheets();
			for (Sheet sheet: sheets) {
				for (int row = 0; row < sheet.getRows(); row++) {
					String xlsCommand = sheet.getCell(COMMAND_COLUMN, row).getContents().trim();
					String xlsTarget = sheet.getCell(TARGET_COLUMN, row).getContents().trim();
					String xlsValue = sheet.getCell(VALUE_COLUMN, row).getContents().trim();
					CommandEnum command = CommandEnum.DUMMY;
					if (xlsCommand.length() > 0) {
						command = CommandEnum.get(xlsCommand);
					}
					String target = xlsTarget;
					String value = xlsValue;
					TestCase testCase = new DefaultTestCase(this.context, row, command, target, value);
					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("******************************");
		}
	}

}
