package org.kne.cloud.network.te;

import java.util.ArrayList;
import java.util.List;

public class DWRRLoadingBalanceAlgorithm<T extends LoadingBalanceEntry<T>> {
	private List<T>entries;

	public List<T> getEntries() {
		return entries;
	}

	public DWRRLoadingBalanceAlgorithm(List<T> entries) {
		super();
		this.entries = entries;
	}

	public List<T> roundEntriesList() {
		List<T>result=new ArrayList<>();
		List<T>tmp=new ArrayList<>(entries.size());
				tmp	.addAll(entries);
		double[] ranges=new double[tmp.size()];
				int rankn=0;
				while(!tmp.isEmpty()) {
					double sum=0.0;
					for (int i = 0; i < tmp.size(); i++) {
						T val=tmp.get(i);
						sum+=val.getWeightAtRank(rankn);
						ranges[i]=sum;
					}
					double selected=generateSelectedNumber(sum);
					for (int i = 0; i < ranges.length; i++) {
						if(selected<=ranges[i]) {
							result.add(tmp.remove(i));
							break;
						}
					}
					
					rankn++;
				}
		//System.out.println(result);
		return result;
	}
	private int counter=0;
	private double generateSelectedNumber(double bound) {
		counter++;
		if(counter>=256) {
			counter=0;
		}
		int counter0=0;
		for (int i = 0; i < 8; i++) {
			counter0<<=1;
			counter0|=(counter>>>i)&1;
		}
		return ((double)counter0)/256*bound;
	}
	/*private Random r=new Random();
	private double generateSelectedNumber(double bound) {
		return r.nextDouble(bound);
	}*/
}
