package dataBase.search;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;

import data.bins.Bins.TYPE_BIN_VALUES;

/**
 * A List of data objects.
 * Can be sorted and limited in length.
 * 
 * @author Krisi
 */
public class DataList<T> {
	
	public static int DefaultTolerance=100;
	
	public ArrayList<T> dataList = new ArrayList<T>(DefaultTolerance);
	private boolean sortAndLimit;
	private Comparator<T> comparator;
	public int lengthLimit, tolerance = DefaultTolerance;
	
	/**
	 * Constructor, simple
	 */
	public DataList(Comparator<T> c){
		this(-1, c);
	}
	/**
	 * Constructor, full
	 * @param lengthLimit - sort&limit activated if parameter > 1
	 */
	public DataList(int lengthLimit, Comparator<T> c){
		
		this.comparator = c;
		sortAndLimit = lengthLimit>1 && tolerance>0;
		
		this.lengthLimit = lengthLimit;
		//this.tolerance = tolerance;
	}
	
	/**
	 * @return actual, internal list size. May be above lengthLimit.
	 */
	public int size(){
		return dataList.size();
	}
	
	/**
	 * Change comparator
	 * @param c - new comparator
	 */
	public void setComparator(Comparator<T> c){
		this.comparator = c;
	}
	
	public void setLimit(int lengthLimit){
		sortAndLimit = lengthLimit>0 && tolerance>0;
		this.lengthLimit = lengthLimit;
	}
	
	/**
	 * Add a single element.
	 * @param data
	 */
	public void add(T data){
		
		dataList.add(data);
		
		if(sortAndLimit && dataList.size() > lengthLimit+tolerance){
			sort();
			limitSize();
		}
	}
	
	/**
	 * Sort list and shorten list to lengthLimit.
	 */
	public void sortAndLimit(){
		sort();
		limitSize();
	}
	
	/**
	 * Delete entries comparator sees as equal.
	 */
	public void deleteDouble(){
		//sortAndLimit();
		for(int i=1; i<dataList.size(); i++){
			
			T t1 = dataList.get(i-1);
			T t2 = dataList.get(i);
			
			if(comparator.compare(t1, t2)==0){
				dataList.remove(i);
				i--;
			}
		}
	}
	
	/**
	 * Sort List
	 */
	private void sort() {
		Collections.sort(dataList, comparator);
	}
	
	/**
	 * Shorten list to lengthLimit
	 */
	private void limitSize(){
		if(lengthLimit>0 && lengthLimit<=dataList.size())
			//dataList = (ArrayList<Data>) dataList.subList(0, lengthLimit);
		while(dataList.size() > lengthLimit)
			dataList.remove(dataList.size()-1);
	}
	
	public ArrayList<T> getList(){
		return dataList;
	}
	
	
	@Override
	public String toString(){
		return this.dataList.toString();
	}
}

