package jp.sourceforge.cfneo.at4ie.impl.xls;

import java.io.File;

import jp.sourceforge.cfneo.at4ie.api.AT4IERuntimeException;
import jp.sourceforge.cfneo.at4ie.api.ActionCommandEnum;
import jp.sourceforge.cfneo.at4ie.api.Context;
import jp.sourceforge.cfneo.at4ie.api.TestCase;
import jp.sourceforge.cfneo.at4ie.api.TestCaseFile;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;

/**
 * Excel形式で渡されたテストケースのファイルのWrapperクラス。
 * @author imaitakafumi
 *
 */
public class ExcelTestCaseFile extends TestCaseFile {

	private static final long serialVersionUID = 1L;

	Logger logger = Logger.getLogger(ExcelTestCaseFile.class);
	private Workbook book;

	/**
	 * コンストラクタ。
	 * @param context
	 * @param filepath
	 */
	public ExcelTestCaseFile(Context context, String filepath) {
		super(context, filepath);
		try {
			book = Workbook.getWorkbook(new File(filepath));
		} catch (Exception e) {
			throw new AT4IERuntimeException(e);
		}
	}

	@Override
	public void destructor() {
		;
	}

	@Override
	public int getRowsCount() {
		ExcelSetting settings = (ExcelSetting) super.getContext();
		Sheet s = this.book.getSheet(settings.getTestCaseSheetName());
		int row = 0;
		for (int i = 0; i < s.getRows(); i++) {
			if ("".equals(s.getCell(0, i).getContents().trim())) {
				break;
			}
			row++;
		}
		return row;
	}

	@Override
	public TestCase getTestCase(int row) {
		ExcelSetting settings = (ExcelSetting) super.getContext();
		Sheet sheet = this.book.getSheet(settings.getTestCaseSheetName());
		ActionCommandEnum command = ActionCommandEnum.get(sheet.getCell(TestCaseFormatEnum.COMMAND.toIntValue(), row)
			.getContents().trim());
		String target = sheet.getCell(TestCaseFormatEnum.TARGET.toIntValue(), row)
				.getContents().trim();
		String value = sheet.getCell(TestCaseFormatEnum.VALUE.toIntValue(), row)
				.getContents().trim();
		logger.debug("ExcelTestCaseFile row=" + row + " command=" + command.toString() + " target=" + target + " value=" + value);
		return new ExcelTestCase(this.getContext(), command, target, value);
	}

}
