package jp.hasc.hasctool.core.runtime.filter.file.table;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.util.CoreUtil;

/**
 * 対象：CSVファイル
 * 各要素のN行目の値をとってくる
 * @author hiro
 */

public class GetNthLineFilter extends AbstractElementFilter{

	int elementNum_;
	int rowNum_;
	String element_;


	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		super.element_ = this.element_;
		String[] row = element_.split(",");
		elementNum_ = row.length;
	}

	String getFeature(String filePath){
		double[] element = new double[elementNum_];
		try{
			InputStream inps = getRuntimeContext().getFileStreamProvider().openInputStream(filePath);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));

			for(int i=0; i<rowNum_; i++){
				String line = bufferedReader.readLine();
				if(line == null)break;
				if(i == rowNum_-1){
					String[] row = line.split(",");
					for(int j=0; j<elementNum_; j++){
						element[j] = Double.parseDouble(row[j+1]);
					}
				}
			}
			bufferedReader.close();
			inps.close();
		} catch (IOException ex) {
			CoreUtil.throwAsRuntimeException(ex);
		} catch (RuntimeException ex) {
		}
		String row_ = "";
		for(int i=0; i<elementNum_; i++){
			if(i!=0){
				row_ += "," + element[i];
			}else{
				row_ += element[i];
			}
		}
		return row_;
	}

	public void setElement(String element){
		element_ = element;
	}

	public void setRowNum(int num){
		rowNum_ = num;
	}



}
