package com.example.steeringhelper;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

import org.opencv.core.Point;

public class InfoCollector {
	public static long MAX_COUNT = 10;
	
	private static Object lock_traces = new Object();
	private static Object lock_directions = new Object();
	// here x means the x axis of the middle point, and y means the width of the surfaceview
	private static Deque<Point> traces = new ArrayDeque<Point>();
	private static Deque<Integer> directions = new ArrayDeque<Integer>();
	
	public static void AddTrace(Point p)
	{
		synchronized (lock_traces){
			while(traces.size() >= MAX_COUNT){
				traces.removeFirst();
			}
			traces.addLast(p);
		}
	}
	
	// 0 means in the middle, negative means left, positive means right
	public static int GetTraceOffset()
	{
		int leftCount = 0;
		int rightCount = 0;
		int centerCount = 0;
		synchronized (lock_traces){
			Iterator<Point> iter = traces.iterator();
			while(iter.hasNext()){
				Point p = (Point)iter.next();
				if(p.x < (p.y / 2 - p.y / 10)){
					++leftCount;
				}else if(p.x > (p.y / 2 + p.y / 10)){
					++rightCount;
				}else{
					++centerCount;
				}
			}
		}
		
		if(leftCount > rightCount){
			if(leftCount > centerCount){
				return -1;
			}
		}else{
			if(rightCount > centerCount){
				return 1;
			}
		}
		
		return 0;
	}
	
	public static void AddDirection(int d)
	{
		synchronized (lock_directions){
			while(directions.size() >= MAX_COUNT){
				directions.removeFirst();
			}
			directions.addLast(d);
		}
	}
	
	// 1 means clockwise, -1 means anti-clockwise
	public static int GetDirection()
	{
		int postiveCount = 0;
		int negativeCount = 0;
		int centerCount = 0;
		synchronized (lock_directions){
			if(directions.size() > 0){
				int current = directions.removeLast();
				Iterator<Integer> iter = directions.iterator();
				while(iter.hasNext()){
					int d = (int)iter.next();
					if(current < (d - 10)){
						++negativeCount;
					}else if(current > (d + 10)){
						++postiveCount;
					}else{
						++centerCount;
					}
				}
				directions.addLast(current);
			}
		}
		
		if(negativeCount > postiveCount){
			if(negativeCount > centerCount){
				return -1;
			}
		}else{
			if(postiveCount > centerCount){
				return 1;
			}
		}
		
		return 0;
	}
}
