package main;

import java.util.Arrays;
import java.util.HashMap;

import ARMA.ARMA;
import KalmanFilterJava.KalmanFilterJava;
import com.mathworks.toolbox.javabuilder.*;

import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.UpdateListener;

public class MyListener implements UpdateListener {

	Integer windowLength = 10;
	Integer CoefficientLength = 8;
	EventBean[] currentEvents = new EventBean[windowLength];
	Integer cursor = 0;

	ARMA arma = null;
	KalmanFilterJava kalman = null;

	public MyListener() {
		super();
		// TODO Auto-generated constructor stub
		try {
			this.arma = new ARMA();
		} catch (MWException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			this.kalman = new KalmanFilterJava();
		} catch (MWException e1) {
//			 TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

	public void update(EventBean[] newEvents, EventBean[] oldEvents) {
		
		

		if (cursor < windowLength) {
			currentEvents[cursor] = newEvents[0];
			cursor++;
			System.out.println("First " + windowLength.toString()
					+ " Samples (skipped). filling buffer #"
					+ cursor.toString());
			System.out.println(newEvents[0].getUnderlying());
		} else {
			// Read Buffer
			Double[] x = new Double[windowLength + 1];
			Double[] y = new Double[windowLength + 1];
			for (int k = 0; k < windowLength; k++) {
				x[k] = (Double) currentEvents[k].get("FC062APVR");
				y[k] = (Double) currentEvents[k].get("FI061APVR");
			}
			x[windowLength] = (Double) newEvents[0].get("FC062APVR");
			y[windowLength] = (Double) newEvents[0].get("FI061APVR");

			Object[] output = null;

			try {
				output = arma.compute(1, x, y, windowLength,
						CoefficientLength);
			} catch (MWException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
					
			Object[] o = null;
			
			try {
				o = kalman.KalmanFilterJava(1, x, y);
			} catch (MWException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			MWLogicalArray unPack = (MWLogicalArray) o[0];
			//boolean err =  unPack.getfield(8);
//			MWNumericArray errorRaw = (MWNumericArray) unPacked.getField(4);
//			double[] X = Xraw.getDoubleData();
//			double erre = err.getDouble();
			
			
			
			MWStructArray unPacked = (MWStructArray) output[0];
			MWNumericArray Xraw = (MWNumericArray) unPacked.getField(1);
			MWNumericArray errorRaw = (MWNumericArray) unPacked.getField(4);
			double[] X = Xraw.getDoubleData();
			double error = errorRaw.getDouble();
		
//			for (int k = 0; k < windowLength - 1; k++) {
//				currentEvents[k] = currentEvents[k + 1];
//			}
//			currentEvents[windowLength - 1] = newEvents[0];


			System.out.println("x Matrix = " + Arrays.toString(X) + ". Error = "
					+ Double.toString(error));
			System.out.println(newEvents[0].getUnderlying());
			cursor=0;
		}
		
		
		
		
		

	

	}

}
