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(c, -1);
	}
	/**
	 * Constructor, full
	 * @param lengthLimit - sort&limit activated if parameter > 0
	 */
	public DataList(Comparator<T> c, int lengthLimit){
		
		this.comparator = c;
		sortAndLimit = lengthLimit>0 && 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();
		}
	}
	
//	/**
//	 * @param sorted - true if list should be sorted
//	 */
//	public void setSortAndLimit(boolean sortAndLimit){
//		
//		if(!this.sortAndLimit && sortAndLimit){
//			sort();
//			limitSize();
//		}
//		
//		this.sortAndLimit = sortAndLimit;
//	}
	
	public void sortAndLimit(){
		sort();
		limitSize();
	}
	
	
	/**
	 * 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 void relativeValues(){
//		for(T data : dataList){
//			data.bins.valueAction(TYPE_BIN_VALUES.relative1);
//			//data.bins.valuesRelative1();
//		}
//	}
	
	public ArrayList<T> getList(){
		return dataList;
	}
	
}

