package com.bernard.greposimu;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import com.bernard.greposimu.model.game.Identified;

public class Utils {

	public static final double poly5(double a0, double a1, double a2, double a3, double a4, double a5, double x) {
		return 
			a0 +
			a1 * x +
			a2 * x * x +
			a3 * x * x * x +
			a4 * x * x * x * x +
			a5 * x * x * x * x * x;
	}
	
	public static final <T extends Identified> T getIdentified(Set<T> set, String id) {
		return set.stream().filter(x -> x.getId().equals(id)).findAny().orElse(null);
	}
	
	public static final <E extends Enum<E>> EnumSet<E> toEnumSet(Class<E> c,Set<E> set){
		if(set.isEmpty())
			return EnumSet.noneOf(c);
		else
			return EnumSet.copyOf(set);
	}
	
	public static final <T> Map<T,Boolean> setToMap(Set<T> set){
		return new AbstractMap<T,Boolean>() {

			@Override
			public Set<Entry<T, Boolean>> entrySet() {
				return new AbstractSet<Map.Entry<T,Boolean>>() {

					@Override
					public Iterator<Entry<T, Boolean>> iterator() {
						Iterator<T> it = set.iterator();
						return new Iterator<Map.Entry<T,Boolean>>() {

							@Override
							public boolean hasNext() {
								return it.hasNext();
							}

							@Override
							public Entry<T, Boolean> next() {
								// TODO Auto-generated method stub
								return new AbstractMap.SimpleEntry<>(it.next(), true);
							}
							
							@Override
							public void remove() {
								it.remove();
							}
						};
					}

					@Override
					public int size() {
						return set.size();
					}
				};
			}
			
			@Override
			public Boolean put(T k, Boolean v) {
				Boolean old = set.contains(k);
				if(v != null && v)
					set.add(k);
				return old;
			}
			
		};
	}
	
	public static <E> E randFromSet(Random r, Set<E> set) {
		E el = set.stream().sorted().skip(r.nextInt(set.size())).findFirst().get();
	    return el;
	}
}
