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

import jp.hasc.hasctool.core.data.SignalMessage;
import jp.hasc.hasctool.core.data.VectorSignalMessage;
import jp.hasc.hasctool.core.data.VectorSignalMessages;

/**
 * ベクトルを線形補間して返すSignalInterpolatorです
 * @author iwasaki
 */
public class LinearVectorInterporator implements SignalInterpolator {

	private VectorSignalMessage previous_=null, next_=null;

	@Override
	public boolean addSample(SignalMessage message) {
		if (message instanceof VectorSignalMessage) {
			previous_=next_;
			next_ = (VectorSignalMessage) message;
			return true;
		}else{
			return false;
		}
	}

	@Override
	public SignalMessage getAtTime(long time) {
		if (next_==null) return null;
		if (previous_==null) return next_.createDelayedElement(time-next_.getTime());
		long ntime = next_.getTime();
		long ptime = previous_.getTime();
		if (ntime-ptime==0) return next_;
		double p=((double)(time-ptime))/((double)(ntime-ptime));
		int vsize = Math.min(previous_.getVectorSize(), next_.getVectorSize());
		if (vsize==1) {
			double val=previous_.getVectorElement(0)*(1-p)+next_.getVectorElement(0)*p;
			return VectorSignalMessages.createScalar(time, val);
		}else{
			double vals[]=new double[vsize];
			for(int i=0;i<vsize;++i) {
				vals[i]=previous_.getVectorElement(i)*(1-p)+next_.getVectorElement(i)*p;
			}
			return VectorSignalMessages.create(time, vals, false);
		}
	}

}
