package speiger.src.collections.shorts.sets;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;

import speiger.src.collections.shorts.collections.ShortBidirectionalIterator;
import speiger.src.collections.shorts.collections.ShortCollection;
import speiger.src.collections.shorts.collections.ShortIterator;
import speiger.src.collections.shorts.functions.ShortConsumer;
import speiger.src.collections.shorts.functions.OptionalShort;
import speiger.src.collections.ints.functions.consumer.IntShortConsumer;
import speiger.src.collections.objects.functions.consumer.ObjectShortConsumer;
import speiger.src.collections.shorts.functions.function.ShortPredicate;
import speiger.src.collections.shorts.functions.function.ShortShortUnaryOperator;
import speiger.src.collections.shorts.lists.ShortListIterator;
import speiger.src.collections.shorts.utils.ShortArrays;
import speiger.src.collections.objects.utils.ObjectArrays;
import speiger.src.collections.shorts.utils.ShortIterators;

import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.SanityChecks;

/**
 * A Type Specific Custom implementation of the HashSet
 * Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys.
 * Extra to that there is a couple quality of life functions provided
 */
public class ImmutableShortOpenHashSet extends AbstractShortSet implements ShortOrderedSet
{
	/** The Backing keys array */
	protected transient short[] keys;
	/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
	protected transient long[] links;
	/** If a null value is present */
	protected transient boolean containsNull;
	/** Index of the Null Value */
	protected transient int nullIndex;
	/** Max Index that is allowed to be searched through nullIndex - 1 */
	protected transient int mask;
	/** Amount of Elements stored in the HashSet */
	protected int size;
	/** The First Index in the Map */
	protected int firstIndex = -1;
	/** The Last Index in the Map */
	protected int lastIndex = -1;
	
	/**
	 * Helper constructor to optimize the copying
	 * Only accessible through implementations
	 */
	protected ImmutableShortOpenHashSet() {}
	
	/**
	 * Helper constructor that allow to create a set from unboxed values
	 * @param array the elements that should be put into the set
	 */
	public ImmutableShortOpenHashSet(short[] array) {
		this(array, 0, array.length, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * Helper constructor that allow to create a set from unboxed values
	 * @param array the elements that should be put into the set
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public ImmutableShortOpenHashSet(short[] array, float loadFactor) {
		this(array, 0, array.length, loadFactor);
	}
	
	/**
	 * Helper constructor that allow to create a set from unboxed values
	 * @param array the elements that should be put into the set
	 * @param offset the starting index within the array that should be used
	 * @param length the amount of elements used from the array
	 * @throws IllegalStateException if offset and length causes to step outside of the arrays range
	 */
	public ImmutableShortOpenHashSet(short[] array, int offset, int length) {
		this(array, offset, length, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * Helper constructor that allow to create a set from unboxed values
	 * @param array the elements that should be put into the set
	 * @param offset the starting index within the array that should be used
	 * @param length the amount of elements used from the array
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 * @throws IllegalStateException if offset and length causes to step outside of the arrays range
	 */
	public ImmutableShortOpenHashSet(short[] array, int offset, int length, float loadFactor) {
		init(array, offset, length, loadFactor);
	}
	
	/**
	 * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
	 * @param collection the set the elements should be added to the Set
	 */
	@Deprecated
	public ImmutableShortOpenHashSet(Collection<? extends Short> collection) {
		this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
	 * @param collection the set the elements should be added to the Set
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	@Deprecated
	public ImmutableShortOpenHashSet(Collection<? extends Short> collection, float loadFactor) {
		init(ShortArrays.unwrap(collection.toArray(new Short[collection.size()])), 0, collection.size(), loadFactor);
	}
	
	/**
	 * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
	 * @param collection the set the elements should be added to the Set
	 */
	public ImmutableShortOpenHashSet(ShortCollection collection) {
		this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
	 * @param collection the set the elements should be added to the Set
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public ImmutableShortOpenHashSet(ShortCollection collection, float loadFactor) {
		init(collection.toShortArray(new short[collection.size()]), 0, collection.size(), loadFactor);
	}
	
	/**
	 * A Helper constructor that allows to create a set from a iterator of an unknown size
	 * @param iterator the elements that should be added to the set
	 */
	public ImmutableShortOpenHashSet(Iterator<Short> iterator) {
		this(iterator, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * A Helper constructor that allows to create a set from a iterator of an unknown size
	 * @param iterator the elements that should be added to the set
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public ImmutableShortOpenHashSet(Iterator<Short> iterator, float loadFactor) {
		this(ShortIterators.wrap(iterator), loadFactor);
	}
	/**
	 * A Helper constructor that allows to create a set from a iterator of an unknown size
	 * @param iterator the elements that should be added to the set
	 */
	public ImmutableShortOpenHashSet(ShortIterator iterator) {
		this(iterator, HashUtil.DEFAULT_LOAD_FACTOR);
	}
	
	/**
	 * A Helper constructor that allows to create a set from a iterator of an unknown size
	 * @param iterator the elements that should be added to the set
	 * @param loadFactor the percentage of how full the backing array can be before they resize
	 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
	 */
	public ImmutableShortOpenHashSet(ShortIterator iterator, float loadFactor) {
		short[] array = ShortArrays.pour(iterator);
		init(array, 0, array.length, loadFactor);
	}
	
	protected void init(short[] a, int offset, int length, float loadFactor) {
		SanityChecks.checkArrayCapacity(a.length, offset, length);
		int newSize = HashUtil.arraySize(length+1, loadFactor);
		int newMask = newSize - 1;
		short[] newKeys = new short[newSize + 1];
		long[] newLinks = new long[newSize + 1];
		int prev = -1;
		for(int i = offset,m=offset+length;i<m;i++)
		{
			short o = a[i];
			if(o == (short)0) {
				if(!containsNull) {
					size++;
					if(prev != -1) {
						newLinks[prev] ^= ((newLinks[prev] ^ (newSize & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
						newLinks[newSize] ^= ((newLinks[newSize] ^ ((prev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
						prev = newSize;
					}
					else {
						prev = firstIndex = newSize;
						newLinks[newSize] = -1L;
					}
				}
				containsNull = true;
				continue;
			}
			boolean found = true;
			int pos = HashUtil.mix(Short.hashCode(o)) & newMask;
			short current = newKeys[pos];
			if(current != (short)0) {
				if(current == o) continue;
				while((current = newKeys[pos = (++pos & newMask)]) != (short)0) {
					if(current == o) {
						found = false;
						break;
					}
				}
			}
			if(found) {
				size++;
				newKeys[pos] = o;
				if(prev != -1) {
					newLinks[prev] ^= ((newLinks[prev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
					newLinks[pos] ^= ((newLinks[pos] ^ ((prev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
					prev = pos;
				}
				else {
					prev = firstIndex = pos;
					newLinks[pos] = -1L;
				}
			}
		}
		nullIndex = newSize;
		mask = newMask;
		keys = newKeys;
		links = newLinks;
		lastIndex = prev;
		if(prev != -1) newLinks[prev] |= 0xFFFFFFFFL;
	}
	
	@Override
	public boolean add(short o) { throw new UnsupportedOperationException(); }
	@Override
	@Deprecated
	public boolean addAll(Collection<? extends Short> c) { throw new UnsupportedOperationException(); }
	@Override
	public boolean addAll(ShortCollection c) { throw new UnsupportedOperationException(); }
	@Override
	public void addFirst(short o) { throw new UnsupportedOperationException(); }
	@Override
	public void addLast(short o) { throw new UnsupportedOperationException(); }
	@Override
	public boolean addAndMoveToFirst(short o) { throw new UnsupportedOperationException(); }
	@Override
	public boolean addAndMoveToLast(short o) { throw new UnsupportedOperationException(); }
	@Override
	public boolean moveToFirst(short o) { throw new UnsupportedOperationException(); }
	@Override
	public boolean moveToLast(short o) { throw new UnsupportedOperationException(); }
	
	@Override
	public boolean contains(Object o) {
		if(o == null) return false;
		if(o instanceof Short && ((Short)o).shortValue() == (short)0) return containsNull;
		int pos = HashUtil.mix(o.hashCode()) & mask;
		short current = keys[pos];
		if(current == (short)0) return false;
		if(Objects.equals(o, Short.valueOf(current))) return true;
		while(true) {
			if((current = keys[pos = (++pos & mask)]) == (short)0) return false;
			else if(Objects.equals(o, Short.valueOf(current))) return true;
		}
	}
	
	@Override
	public short getFirstShort() {
		if(size == 0) throw new NoSuchElementException();
		return keys[firstIndex];
	}
	
	@Override
	public short removeFirstShort() { throw new UnsupportedOperationException(); }
	
	@Override
	public short getLastShort() {
		if(size == 0) throw new NoSuchElementException();
		return keys[lastIndex];
	}
	
	@Override
	public short removeLastShort() { throw new UnsupportedOperationException(); }
	@Override
	public boolean remove(Object o) { throw new UnsupportedOperationException(); }

	@Override
	public boolean contains(short o) {
		if(o == (short)0) return containsNull;
		int pos = HashUtil.mix(Short.hashCode(o)) & mask;
		short current = keys[pos];
		if(current == (short)0) return false;
		if(current == o) return true;
		while(true) {
			if((current = keys[pos = (++pos & mask)]) == (short)0) return false;
			else if(current == o) return true;
		}
	}
	
	@Override
	public boolean remove(short o) { throw new UnsupportedOperationException(); }
	
	@Override
	public void forEach(ShortConsumer action) {
		Objects.requireNonNull(action);
		int index = firstIndex;
		while(index != -1) {
			action.accept(keys[index]);
			index = (int)links[index];
		}
	}
	
	@Override
	public void forEachIndexed(IntShortConsumer action) {
		Objects.requireNonNull(action);
		int count = 0;
		int index = firstIndex;
		while(index != -1) {
			action.accept(count++, keys[index]);
			index = (int)links[index];
		}
	}
	
	@Override
	public <E> void forEach(E input, ObjectShortConsumer<E> action) {
		Objects.requireNonNull(action);
		int index = firstIndex;
		while(index != -1) {
			action.accept(input, keys[index]);
			index = (int)links[index];
		}
	}
	
	@Override
	public boolean matchesAny(ShortPredicate filter) {
		Objects.requireNonNull(filter);
		int index = firstIndex;
		while(index != -1) {
			if(filter.test(keys[index])) return true;
			index = (int)links[index];
		}
		return false;
	}
	
	@Override
	public boolean matchesNone(ShortPredicate filter) {
		Objects.requireNonNull(filter);
		int index = firstIndex;
		while(index != -1) {
			if(filter.test(keys[index])) return false;
			index = (int)links[index];
		}
		return true;
	}
	
	@Override
	public boolean matchesAll(ShortPredicate filter) {
		Objects.requireNonNull(filter);
		int index = firstIndex;
		while(index != -1) {
			if(!filter.test(keys[index])) return false;
			index = (int)links[index];
		}
		return true;
	}
	
	@Override
	public short reduce(short identity, ShortShortUnaryOperator operator) {
		Objects.requireNonNull(operator);
		short state = identity;
		int index = firstIndex;
		while(index != -1) {
			state = operator.applyAsShort(state, keys[index]);
			index = (int)links[index];
		}
		return state;
	}
	
	@Override
	public OptionalShort reduce(ShortShortUnaryOperator operator) {
		Objects.requireNonNull(operator);
		short state = (short)0;
		boolean empty = true;
		int index = firstIndex;
		while(index != -1) {
			if(empty) {
				state = keys[index];
				empty = false;
			}
			else state = operator.applyAsShort(state, keys[index]);
			index = (int)links[index];
		}
		return empty ? OptionalShort.empty() : OptionalShort.of(state);
	}
	
	@Override
	public OptionalShort findFirst(ShortPredicate filter) {
		Objects.requireNonNull(filter);
		int index = firstIndex;
		while(index != -1) {
			if(filter.test(keys[index])) return OptionalShort.of(keys[index]);
			index = (int)links[index];
		}
		return OptionalShort.empty();
	}
	
	@Override
	public int count(ShortPredicate filter) {
		Objects.requireNonNull(filter);
		int result = 0;
		int index = firstIndex;
		while(index != -1) {
			if(filter.test(keys[index])) result++;
			index = (int)links[index];
		}
		return result;
	}
	
	@Override
	public ShortListIterator iterator() {
		return new SetIterator(true);
	}
	
	@Override
	public ShortListIterator reverseIterator() {
		return new SetIterator(false);
	}
	
	@Override
	public ShortBidirectionalIterator iterator(short fromElement) {
		return new SetIterator(fromElement);
	}
	
	@Override
	public short[] toShortArray(short[] a) {
		if(a == null || a.length < size()) a = new short[size()];
		for(int i = 0, index = firstIndex;index != -1;i++,index = (int)links[index]) {
			a[i] = keys[index];
		}
		if (a.length > size) a[size] = (short)0;
		return a;
	}
	
	@Override
	@Deprecated
	public Object[] toArray() {
		if(isEmpty()) return ObjectArrays.EMPTY_ARRAY;
		Object[] obj = new Object[size()];
		for(int i = 0, index = firstIndex;index != -1;i++,index = (int)links[index]) {
			obj[i] = Short.valueOf(keys[index]);
		}
		return obj;
	}
	
	@Override
	@Deprecated
	public <E> E[] toArray(E[] a) {
		if(a == null) a = (E[])new Object[size()];
		else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
		for(int i = 0, index = firstIndex;index != -1;i++,index = (int)links[index]) {
			a[i] = (E)Short.valueOf(keys[index]);
		}
		if (a.length > size) a[size] = null;
		return a;
	}
	
	@Override
	public ImmutableShortOpenHashSet copy() {
		ImmutableShortOpenHashSet set = new ImmutableShortOpenHashSet();
		set.containsNull = containsNull;
		set.firstIndex = firstIndex;
		set.lastIndex = lastIndex;
		set.size = size;
		set.mask = mask;
		set.nullIndex = nullIndex;
		set.keys = Arrays.copyOf(keys, keys.length);
		set.links = Arrays.copyOf(links, links.length);
		return set;
	}
	
	@Override
	public void clear() { throw new UnsupportedOperationException(); }
	
	@Override
	public int size() {
		return size;
	}

	private class SetIterator implements ShortListIterator {
		boolean forward;
		int previous = -1;
		int next = -1;
		int current = -1;
		int index = -1;
		
		SetIterator(boolean start) {
			this.forward = start;
			if(start) next = firstIndex;
			else previous = lastIndex;
		}
		
		SetIterator(short from) {
			this.forward = true;
			if(from == (short)0) {
				if(containsNull) {
					next = (int) links[nullIndex];
					previous = nullIndex;
				}
				else throw new NoSuchElementException("The null element is not in the set");
			}
			else if(keys[lastIndex] == from) {
				previous = lastIndex;
				index = size;
			}
			else {
				int pos = HashUtil.mix(Short.hashCode(from)) & mask;
				while(keys[pos] != (short)0) {
					if(keys[pos] == from) {
						next = (int)links[pos];
						previous = pos;
						break;
					}
					pos = ++pos & mask;
				}
				if(previous == -1 && next == -1)
					throw new NoSuchElementException("The element was not found");
			}
		}
		
		@Override
		public int skip(int amount) {
			int result = forward ? moveForward(amount) : moveBackwards(amount);
			if(index >= 0) index+=result;
			return result;
		}
		
		@Override
		public int back(int amount) {
			int result = forward ? moveBackwards(amount) : moveForward(amount);
			if(index >= 0) index-=result;
			return result;
		}
		
		private int moveForward(int amount) {
			int result = 0;
			while(next != -1 && result != amount) {
				current = previous = next;
				next = (int)(links[current]);
				result++;
			}
			return result;
		}
		
		private int moveBackwards(int amount) {
			int result = 0;
			while(previous != -1 && result != amount) {
				current = next = previous;
				previous = (int)(links[current] >> 32);
				result++;
			}
			return result;
		}
		
		@Override
		public boolean hasNext() {
			return (forward ? next : previous) != -1;
		}

		@Override
		public boolean hasPrevious() {
			return (forward ? previous : next) != -1;
		}
		
		@Override
		public int nextIndex() {
			ensureIndexKnown();
			if(forward) return index;
			return size - index;
		}
		
		@Override
		public int previousIndex() {
			ensureIndexKnown();
			if(forward) return index-1;
			return (size - index)-1;
		}
		
		@Override
		public void remove() { throw new UnsupportedOperationException(); }
		
		@Override
		public short previousShort() {
			if(!hasPrevious()) throw new NoSuchElementException();
			if(forward) moveBackwards();
			else moveForwards();
			if(index >= 0) index--;
			return keys[current];
		}

		@Override
		public short nextShort() {
			if(!hasNext()) throw new NoSuchElementException();
			if(forward) moveForwards();
			else moveBackwards();
			if(index >= 0) index++;
			return keys[current];
		}
		
		private void moveBackwards() {
			current = next = previous;
			previous = (int)(links[current] >> 32);
		}
		
		private void moveForwards() {
			current = previous = next;
			next = (int)(links[current]);
		}
		
		private void ensureIndexKnown() {
			if(index == -1) {
				if(previous == -1) {
					index = 0;
				}
				else if(next == -1) {
					index = size;
				}
				else {
					index = 1;
					for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++);
				}
			}
		}
		
		@Override
		public void set(short e) { throw new UnsupportedOperationException(); }

		@Override
		public void add(short e) { throw new UnsupportedOperationException(); }
	}
}