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ファイルから傾き情報を取得する
 * ｃｓｖファイルを対象(time,x,y,z)
 * @author hiro
 */

public class AngleElementFilter extends AbstractElementFilter{

	int axisNum_ = 3;
	String title_ = "atan(y/x),atan(z/y),atan(x/z)";

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		super.element_ = this.title_;
	}

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

			while(true){
				String line = bufferedReader.readLine();
				if (line == null) {
					break;
				} else {
					String[] row = line.split(",");
					for(int i=0; i<axisNum_; i++){
						element[i] = Double.parseDouble(row[i+1]);
					}
					for(int j=0; j<axisNum_; j++){
						int next = (j+1) % axisNum_;
						if(element[j] != 0){
							angle[j] += Math.atan((element[next]/element[j]));
							count[j]++;
						}
					}
				}
			}
			bufferedReader.close();
			inps.close();
		} catch (IOException ex) {
			CoreUtil.throwAsRuntimeException(ex);
		} catch (RuntimeException ex) {
		}
		String row_ = "";
		for(int i=0; i<axisNum_; i++){
			angle[i] /= count[i];
			if(i!=0){
				row_ += "," + angle[i];
			}else{
				row_ += angle[i];
			}
		}
		return row_;
	}
}
