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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import jp.sourceforge.cfneo.at4ie.api.AT4IERuntimeException;
import jp.sourceforge.cfneo.at4ie.api.Context;
import jp.sourceforge.cfneo.at4ie.api.TestCase;
import jp.sourceforge.cfneo.at4ie.api.TestCaseFile;

import org.apache.log4j.Logger;


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

	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(CsvTestCaseFile.class);

	private Map<String, String> rowMap;

	/**
	 * コンストラクタ。
	 * @param filepath
	 */
	public CsvTestCaseFile(Context context, String filepath) {
		super(context, filepath);
		try {
			this.rowMap = new HashMap<String, String>();
			BufferedReader br = new BufferedReader(new FileReader(this));
			int row = 0;
			String line;
			while ((line = br.readLine()) != null) {
				if (row >= this.getContext().getStartRow()
						&& line.substring(0, 1).equals("#") == false
						&& line.trim().length() > 0) {
					String key = String.valueOf(row);
					logger.debug("[" + row + "] " + line + " /key=" + key);
					this.rowMap.put(key, line);
				}
				row++;
			}
			br.close();
			this.setRowsCount(row);
			logger.debug("this.rowsCount=" + row);
		} catch (IOException e) {
			throw new AT4IERuntimeException(e);
		}
	}

	@Override
	public void destructor() {
		try {
			this.clone();
		} catch (CloneNotSupportedException e) {
			throw new AT4IERuntimeException(e);
		}
	}

	@Override
	public TestCase getTestCase(int row) {
		logger.debug("CsvTestCaseFile row=" + row);
		return CsvTestCase.createTestCase(
				this.getContext(),
				(String) this.rowMap.get(String.valueOf(row)));
	}

}
