package speiger.src.coreengine.math;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import speiger.src.collections.ints.lists.IntList;
import speiger.src.collections.objects.lists.ObjectArrayList;

public class ArrayUtil {
	public static int[] fromTo(int from, int to) {
		int[] result = new int[to - from];
		for(int i = 0,m = result.length;i < m;i++) result[i] = from + i;
		return result;
	}
	
	public static int sum(int... values) {
		int result = 0;
		for(int index : values) result += index;
		return result;
	}
	
	public static byte[] fill(byte[] array, byte value) {
		Arrays.fill(array, value);
		return array;
	}
	
	public static short[] fill(short[] array, short value) {
		Arrays.fill(array, value);
		return array;
	}
	
	public static int[] fill(int[] array, int value) {
		Arrays.fill(array, value);
		return array;
	}
	
	public static long[] fill(long[] array, long value) {
		Arrays.fill(array, value);
		return array;
	}
	
	public static float[] fill(float[] array, float value) {
		Arrays.fill(array, value);
		return array;
	}
	
	public static double[] fill(double[] array, double value) {
		Arrays.fill(array, value);
		return array;
	}
	
	public static byte[] toArray(ByteBuffer buffer) {
		if(buffer.hasArray()) {
			byte[] data = buffer.array();
			if(data.length == buffer.remaining()) return data;
		}
		byte[] data = new byte[buffer.remaining()];
		buffer.get(data);
		return data;
	}
	
	public static byte[] toArray(ByteBuffer buffer, Consumer<ByteBuffer> action) {
		if(buffer.hasArray()) {
			byte[] data = buffer.array();
			if(data.length == buffer.remaining()) {
				action.accept(buffer);
				return data;
			}
		}
		byte[] data = new byte[buffer.remaining()];
		buffer.get(data);
		action.accept(buffer);
		return data;
	}
	
	public static <T extends Comparable<T>> T higher(T key, T value) {
		return key.compareTo(value) < 0 ? value : key;
	}
	
	public static <T extends Comparable<T>> T lower(T key, T value) {
		return key.compareTo(value) > 0 ? value : key;
	}
	
	public static <T> List<T> makeList(IntList indexes, List<T> entries) {
		List<T> result = new ObjectArrayList<T>(indexes.size());
		for(int i = 0,m = indexes.size();i < m;i++) result.add(entries.get(indexes.getInt(i)));
		return result;
	}
}
