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

import jp.hasc.hasctool.core.data.LabelInfo;
import jp.hasc.hasctool.core.data.ScalarSignalMessage;
import jp.hasc.hasctool.core.data.SignalMessage;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.runtime.filter.tick.SampleBasedTickEmitter;

/**
 * ScalarSignalMessageの値が、しきい値より大きい区間に、ラベルをつけるフィルタです
 * @author iwasaki
 */
public class SampleLabelingFilter extends AbstractLabelingFilter {

	private double threthold_=0;
	private String label_="label";
	private ScalarSignalMessage previousHighSignal_=null;
	private LabelInfo currentLabelInfo_=null;
	
	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		// TickEmitterを設定
		setTickEmitter(new SampleBasedTickEmitter(4));
	}

	@Override
	protected void processSignalMessage(SignalMessage message) throws InterruptedException {
		if (message instanceof ScalarSignalMessage) {
			ScalarSignalMessage sig=(ScalarSignalMessage)message;
			double v=sig.getScalarValue();
			if (threthold_<v) {
				if (previousHighSignal_==null) {
					// 信号の立ち上がりを検出した
					currentLabelInfo_=new LabelInfo(label_);
					outputMessage(currentLabelInfo_.createBeginMessage(sig.getTime()));
				}
				previousHighSignal_=sig;
			}else{
				processLowSignal();
			}
		}
	}

	private void processLowSignal() throws InterruptedException {
		if (previousHighSignal_!=null) {
			// 信号の立ち下がりを検出した
			outputMessage(currentLabelInfo_.createEndMessage(previousHighSignal_.getTime()));
			currentLabelInfo_=null;
			previousHighSignal_=null;
		}
	}
	
	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message==SignalMessage.END) {
			// 高い値のまま終了した時にも、ラベルが出力されるように
			processLowSignal();
		}
		super.processMessage(message);
	}

	public double getThrethold() {
		return threthold_;
	}

	public void setThrethold(double threthold) {
		threthold_ = threthold;
	}

	public String getLabel() {
		return label_;
	}

	public void setLabel(String label) {
		label_=label;
	}

}
