package org.mote.wiimote.whiteboard.mouse.smoothing;

import java.awt.Point;

public class AdaptiveExponentialSmoothing implements MouseSmoothingStrategy {
	
	public final static String NAME = "Adaptive Exponential Smoothing";
	
	private static final double alpha = .20d;
	private static final double dAlpha = .1d;
	
	private double x, y, dx, dy;
	private Point last;
	
	public AdaptiveExponentialSmoothing() {
		reset();
	}

	public void reset() {
		x = y = dx = dy = Double.NaN;
		last = null;
	}

	public Point translate(Point p) {
		
		double alpha = AdaptiveExponentialSmoothing.alpha;
		
		if (last == null) {
			dx = dy = 0;
		} else {
			dx += dAlpha*((p.getX() - last.getX()) - dx);
			dy += dAlpha*((p.getY() - last.getY()) - dy);

			alpha = alpha+.015 - (alpha+.015)*(1/(Math.max(Math.abs(dx), Math.abs(dy))+1));
		}
		last = p;
		
		if (Double.isNaN(x)) {
			x = p.getX();
			y = p.getY();
		} else {
			x += alpha*(p.getX() - x);
			y += alpha*(p.getY() - y);
		}
		return new Point((int)Math.round(x), (int)Math.round(y));
	}

}
