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

import jp.hasc.hasctool.core.data.VectorSignalMessage;
import jp.hasc.hasctool.core.data.VectorSignalMessages;
import jp.hasc.hasctool.core.runtime.RuntimeContext;

/**
 * IIRフィルタです
 * @author hiro
 */

public class IIRFilter extends AbstractFilter{
	
	private double[] preElement_;//前回の出力
	private double coefficient_;//フィルタ係数

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		preElement_ = new double[1];//初期設定は1ch
	}

	public void setCoefficient(double val) {
		coefficient_ = val;
		if(coefficient_ < 0) coefficient_ = 0;
		else if(coefficient_ > 1.0) coefficient_ = 1.0;
		preElement_ = new double[1];//初期設定は1ch
	}

	
	private void createData(double[] valAry, int index){
		preElement_ = new double[index];
		if(index > valAry.length){
			for(int i=0; i<valAry.length; i++)preElement_[i] = valAry[i];
		} else {
			for(int i=0; i<index; i++)preElement_[i] = valAry[i];
		}
	}


	private void setData(double val, int index){
		preElement_[index]=val;
	}

	
	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof VectorSignalMessage) {
			// VectorSignalMessageの場合
			VectorSignalMessage vsig=(VectorSignalMessage)message;
			// 新しいベクトルの値を計算
			double[] newValue=new double[vsig.getVectorSize()];
			if(vsig.getVectorSize() != preElement_.length)createData(preElement_, vsig.getVectorSize());
			for(int i=0; i<newValue.length; ++i){
				newValue[i] = coefficient_ * vsig.getVectorElement(i) + (1.0 - coefficient_) * preElement_[i];
				setData(newValue[i], i);
			}
			// 結果を出力
			outputMessage(VectorSignalMessages.create(vsig.getTime(), newValue));
		}else{
			// その他のメッセージ（BEGIN, ENDなど）はそのまま出力
			outputMessage(message);
		}
	}
}
