package speiger.src.collections.chars.maps.abstracts;

import java.util.AbstractMap;
import java.util.Map;
import java.util.Objects;

import speiger.src.collections.chars.collections.CharIterator;
import speiger.src.collections.chars.functions.consumer.CharIntConsumer;
import speiger.src.collections.chars.functions.function.Char2IntFunction;
import speiger.src.collections.chars.functions.function.CharIntUnaryOperator;
import speiger.src.collections.chars.maps.interfaces.Char2IntMap;
import speiger.src.collections.chars.maps.interfaces.Char2IntOrderedMap;
import speiger.src.collections.chars.sets.CharOrderedSet;
import speiger.src.collections.ints.collections.IntOrderedCollection;
import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectOrderedSet;
import speiger.src.collections.chars.sets.AbstractCharSet;
import speiger.src.collections.chars.sets.CharSet;
import speiger.src.collections.chars.utils.maps.Char2IntMaps;
import speiger.src.collections.ints.collections.AbstractIntCollection;
import speiger.src.collections.ints.collections.IntCollection;
import speiger.src.collections.ints.collections.IntIterator;
import speiger.src.collections.ints.functions.function.IntIntUnaryOperator;
import speiger.src.collections.ints.functions.IntSupplier;
import speiger.src.collections.objects.collections.ObjectIterable;
import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.objects.sets.ObjectSet;
import speiger.src.collections.utils.SanityChecks;

/**
 * A Base Implementation of a Type Specific Map to reduce boxing/unboxing
 */
public abstract class AbstractChar2IntMap extends AbstractMap<Character, Integer> implements Char2IntMap
{
	protected int defaultReturnValue = -1;
	
	@Override
	public int getDefaultReturnValue() {
		return defaultReturnValue;
	}
	
	@Override
	public AbstractChar2IntMap setDefaultReturnValue(int v) {
		defaultReturnValue = v;
		return this;
	}
	
	protected ObjectIterable<Char2IntMap.Entry> getFastIterable(Char2IntMap map) {
		return Char2IntMaps.fastIterable(map);
	}
	
	protected ObjectIterator<Char2IntMap.Entry> getFastIterator(Char2IntMap map) {
		return Char2IntMaps.fastIterator(map);
	}
	
	@Override
	public Char2IntMap copy() { 
		throw new UnsupportedOperationException();
	}
	
	@Override
	@Deprecated
	public Integer put(Character key, Integer value) {
		return Integer.valueOf(put(key.charValue(), value.intValue()));
	}
	
	@Override
	public void addToAll(Char2IntMap m) {
		for(Char2IntMap.Entry entry : getFastIterable(m))
			addTo(entry.getCharKey(), entry.getIntValue());
	}
	
	@Override
	public void putAll(Char2IntMap m) {
		for(ObjectIterator<Char2IntMap.Entry> iter = getFastIterator(m);iter.hasNext();) {
			Char2IntMap.Entry entry = iter.next();
			put(entry.getCharKey(), entry.getIntValue());
		}
	}
	
	@Override
	public void putAll(Map<? extends Character, ? extends Integer> m)
	{
		if(m instanceof Char2IntMap) putAll((Char2IntMap)m);
		else super.putAll(m);
	}
	
	@Override
	public void putAll(char[] keys, int[] values, int offset, int size) {
		SanityChecks.checkArrayCapacity(keys.length, offset, size);
		SanityChecks.checkArrayCapacity(values.length, offset, size);
		for(int i = 0;i<size;i++) put(keys[i], values[i]);
	}
	
	@Override
	public void putAll(Character[] keys, Integer[] values, int offset, int size) {
		SanityChecks.checkArrayCapacity(keys.length, offset, size);
		SanityChecks.checkArrayCapacity(values.length, offset, size);
		for(int i = 0;i<size;i++) put(keys[i].charValue(), values[i].intValue());		
	}
	
	@Override
	public void putAllIfAbsent(Char2IntMap m) {
		for(Char2IntMap.Entry entry : getFastIterable(m))
			putIfAbsent(entry.getCharKey(), entry.getIntValue());
	}
	
	
	@Override
	public boolean containsKey(char key) {
		for(CharIterator iter = keySet().iterator();iter.hasNext();)
			if(iter.nextChar() == key) return true;
		return false;
	}
	
	@Override
	public boolean containsValue(int value) {
		for(IntIterator iter = values().iterator();iter.hasNext();)
			if(iter.nextInt() == value) return true;
		return false;
	}
	
	@Override
	public boolean replace(char key, int oldValue, int newValue) {
		int curValue = get(key);
		if (curValue != oldValue || (curValue == getDefaultReturnValue() && !containsKey(key))) {
			return false;
		}
		put(key, newValue);
		return true;
	}

	@Override
	public int replace(char key, int value) {
		int curValue;
		if ((curValue = get(key)) != getDefaultReturnValue() || containsKey(key)) {
			curValue = put(key, value);
		}
		return curValue;
	}
	
	@Override
	public void replaceInts(Char2IntMap m) {
		for(Char2IntMap.Entry entry : getFastIterable(m))
			replace(entry.getCharKey(), entry.getIntValue());
	}
	
	@Override
	public void replaceInts(CharIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		for(ObjectIterator<Char2IntMap.Entry> iter = getFastIterator(this);iter.hasNext();) {
			Char2IntMap.Entry entry = iter.next();
			entry.setValue(mappingFunction.applyAsInt(entry.getCharKey(), entry.getIntValue()));
		}
	}

	@Override
	public int computeInt(char key, CharIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		int newValue = mappingFunction.applyAsInt(key, get(key));
		put(key, newValue);
		return newValue;
	}
	
	@Override
	public int computeIntIfAbsent(char key, Char2IntFunction mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		if(!containsKey(key)) {
			int newValue = mappingFunction.applyAsInt(key);
			put(key, newValue);
			return newValue;
		}
		return get(key);
	}
	
	@Override
	public int supplyIntIfAbsent(char key, IntSupplier valueProvider) {
		Objects.requireNonNull(valueProvider);
		if(!containsKey(key)) {
			int newValue = valueProvider.getAsInt();
			put(key, newValue);
			return newValue;
		}
		return get(key);
	}
	
	@Override
	public int computeIntIfPresent(char key, CharIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		if(containsKey(key)) {
			int newValue = mappingFunction.applyAsInt(key, get(key));
			put(key, newValue);
			return newValue;
		}
		return getDefaultReturnValue();
	}
	
	@Override
	public int computeIntNonDefault(char key, CharIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		int value = get(key);
		int newValue = mappingFunction.applyAsInt(key, value);
		if(newValue == getDefaultReturnValue()) {
			if(value != getDefaultReturnValue() || containsKey(key)) {
				remove(key);
				return getDefaultReturnValue();
			}
			return getDefaultReturnValue();
		}
		put(key, newValue);
		return newValue;
	}
	
	@Override
	public int computeIntIfAbsentNonDefault(char key, Char2IntFunction mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		int value;
		if((value = get(key)) == getDefaultReturnValue() || !containsKey(key)) {
			int newValue = mappingFunction.applyAsInt(key);
			if(newValue != getDefaultReturnValue()) {
				put(key, newValue);
				return newValue;
			}
		}
		return value;
	}
	
	@Override
	public int supplyIntIfAbsentNonDefault(char key, IntSupplier valueProvider) {
		Objects.requireNonNull(valueProvider);
		int value;
		if((value = get(key)) == getDefaultReturnValue() || !containsKey(key)) {
			int newValue = valueProvider.getAsInt();
			if(newValue != getDefaultReturnValue()) {
				put(key, newValue);
				return newValue;
			}
		}
		return value;
	}
	
	@Override
	public int computeIntIfPresentNonDefault(char key, CharIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		int value;
		if((value = get(key)) != getDefaultReturnValue() || containsKey(key)) {
			int newValue = mappingFunction.applyAsInt(key, value);
			if(newValue != getDefaultReturnValue()) {
				put(key, newValue);
				return newValue;
			}
			remove(key);
		}
		return getDefaultReturnValue();
	}
	
	@Override
	public int mergeInt(char key, int value, IntIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		int oldValue = get(key);
		int newValue = oldValue == getDefaultReturnValue() ? value : mappingFunction.applyAsInt(oldValue, value);
		if(newValue == getDefaultReturnValue()) remove(key);
		else put(key, newValue);
		return newValue;
	}
	
	@Override
	public void mergeAllInt(Char2IntMap m, IntIntUnaryOperator mappingFunction) {
		Objects.requireNonNull(mappingFunction);
		for(Char2IntMap.Entry entry : getFastIterable(m)) {
			char key = entry.getCharKey();
			int oldValue = get(key);
			int newValue = oldValue == getDefaultReturnValue() ? entry.getIntValue() : mappingFunction.applyAsInt(oldValue, entry.getIntValue());
			if(newValue == getDefaultReturnValue()) remove(key);
			else put(key, newValue);
		}
	}
	
	@Override
	public Integer get(Object key) {
		return Integer.valueOf(key instanceof Character ? get(((Character)key).charValue()) : getDefaultReturnValue());
	}
	
	@Override
	public Integer getOrDefault(Object key, Integer defaultValue) {
		return Integer.valueOf(key instanceof Character ? getOrDefault(((Character)key).charValue(), defaultValue.intValue()) : getDefaultReturnValue());
	}
	
	@Override
	public int getOrDefault(char key, int defaultValue) {
		int value = get(key);
		return value != getDefaultReturnValue() || containsKey(key) ? value : defaultValue;
	}
	
	
	@Override
	public Integer remove(Object key) {
		return key instanceof Character ? Integer.valueOf(remove(((Character)key).charValue())) : Integer.valueOf(getDefaultReturnValue());
	}
	
	@Override
	public void forEach(CharIntConsumer action) {
		Objects.requireNonNull(action);
		for(ObjectIterator<Char2IntMap.Entry> iter = getFastIterator(this);iter.hasNext();) {
			Char2IntMap.Entry entry = iter.next();
			action.accept(entry.getCharKey(), entry.getIntValue());
		}
	}

	@Override
	public CharSet keySet() {
		return new AbstractCharSet() {
			@Override
			public boolean remove(char o) {
				return AbstractChar2IntMap.this.remove(o) != getDefaultReturnValue();
			}
			
			@Override
			public boolean add(char o) {
				throw new UnsupportedOperationException();
			}
			
			@Override
			public CharIterator iterator() {
				return new CharIterator() {
					ObjectIterator<Char2IntMap.Entry> iter = getFastIterator(AbstractChar2IntMap.this);
					@Override
					public boolean hasNext() {
						return iter.hasNext();
					}

					@Override
					public char nextChar() {
						return iter.next().getCharKey();
					}
					
					@Override
					public void remove() {
						iter.remove();
					}
				};
			}
			
			@Override
			public int size() {
				return AbstractChar2IntMap.this.size();
			}
			
			@Override
			public void clear() {
				AbstractChar2IntMap.this.clear();
			}
		};
	}

	@Override
	public IntCollection values() {
		return new AbstractIntCollection() {
			@Override
			public boolean add(int o) {
				throw new UnsupportedOperationException();
			}
			
			@Override
			public int size() {
				return AbstractChar2IntMap.this.size();
			}
			
			@Override
			public void clear() {
				AbstractChar2IntMap.this.clear();
			}
			
			@Override
			public IntIterator iterator() {
				return new IntIterator() {
					ObjectIterator<Char2IntMap.Entry> iter = getFastIterator(AbstractChar2IntMap.this);
					@Override
					public boolean hasNext() {
						return iter.hasNext();
					}
					
					@Override
					public int nextInt() {
						return iter.next().getIntValue();
					}
					
					@Override
					public void remove() {
						iter.remove();
					}
				};
			}
		};
	}
	
	@Override
	@SuppressWarnings("rawtypes")
	public ObjectSet<Map.Entry<Character, Integer>> entrySet() {
		return (ObjectSet)char2IntEntrySet();
	}

	@Override
	public boolean equals(Object o) {
		if(o == this) return true;
		if(o instanceof Map) {
			if(size() != ((Map<?, ?>)o).size()) return false;
			if(o instanceof Char2IntMap) return char2IntEntrySet().containsAll(((Char2IntMap)o).char2IntEntrySet());
			return char2IntEntrySet().containsAll(((Map<?, ?>)o).entrySet());
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		int hash = 0;
		ObjectIterator<Char2IntMap.Entry> iter = getFastIterator(this);
		while(iter.hasNext()) hash += iter.next().hashCode();
		return hash;
	}
	
	public static class ReversedChar2IntOrderedMap extends AbstractChar2IntMap implements Char2IntOrderedMap {
		Char2IntOrderedMap map;
		
		public ReversedChar2IntOrderedMap(Char2IntOrderedMap map) {
			this.map = map;
		}
		@Override
		public AbstractChar2IntMap setDefaultReturnValue(int v) {
			map.setDefaultReturnValue(v);
			return this;
		}
		@Override
		public int getDefaultReturnValue() { return map.getDefaultReturnValue(); }
		@Override
		public Char2IntOrderedMap copy() { throw new UnsupportedOperationException(); }
		@Override
		public int put(char key, int value) { return map.put(key, value); }
		@Override
		public int putIfAbsent(char key, int value) { return map.putIfAbsent(key, value); }
		@Override
		public int addTo(char key, int value) { return map.addTo(key, value); }
		@Override
		public int subFrom(char key, int value) { return map.subFrom(key, value); }
		@Override
		public int remove(char key) { return map.remove(key); }
		@Override
		public boolean remove(char key, int value) { return map.remove(key, value); }
		@Override
		public int removeOrDefault(char key, int defaultValue) { return map.removeOrDefault(key, defaultValue); }
		@Override
		public boolean containsKey(char key) { return map.containsKey(key); }
		@Override
		public boolean containsValue(int value) { return map.containsValue(value); }
		@Override
		public boolean replace(char key, int oldValue, int newValue) { return map.replace(key, oldValue, newValue); }
		@Override
		public int replace(char key, int value) { return map.replace(key, value); }
		@Override
		public void replaceInts(Char2IntMap m) { map.replaceInts(m); }
		@Override
		public void replaceInts(CharIntUnaryOperator mappingFunction) { map.replaceInts(mappingFunction); }
		@Override
		public int computeInt(char key, CharIntUnaryOperator mappingFunction) { return map.computeInt(key, mappingFunction); }
		@Override
		public int computeIntIfAbsent(char key, Char2IntFunction mappingFunction) { return map.computeIntIfAbsent(key, mappingFunction); }
		@Override
		public int supplyIntIfAbsent(char key, IntSupplier valueProvider) { return map.supplyIntIfAbsent(key, valueProvider); }
		@Override
		public int computeIntIfPresent(char key, CharIntUnaryOperator mappingFunction) { return map.computeIntIfPresent(key, mappingFunction); }
		@Override
		public int computeIntNonDefault(char key, CharIntUnaryOperator mappingFunction) { return map.computeIntNonDefault(key, mappingFunction); }
		@Override
		public int computeIntIfAbsentNonDefault(char key, Char2IntFunction mappingFunction) { return map.computeIntIfAbsentNonDefault(key, mappingFunction); }
		@Override
		public int supplyIntIfAbsentNonDefault(char key, IntSupplier valueProvider) { return map.supplyIntIfAbsentNonDefault(key, valueProvider); }
		@Override
		public int computeIntIfPresentNonDefault(char key, CharIntUnaryOperator mappingFunction) { return map.computeIntIfPresentNonDefault(key, mappingFunction); }
		@Override
		public int mergeInt(char key, int value, IntIntUnaryOperator mappingFunction) { return map.mergeInt(key, value, mappingFunction); }
		@Override
		public int getOrDefault(char key, int defaultValue) { return map.getOrDefault(key, defaultValue); }
		@Override
		public int get(char key) { return map.get(key); }
		@Override
		public int putAndMoveToFirst(char key, int value) { return map.putAndMoveToLast(key, value); }
		@Override
		public int putAndMoveToLast(char key, int value) { return map.putAndMoveToFirst(key, value); }
		@Override
		public int putFirst(char key, int value) { return map.putLast(key, value); }
		@Override
		public int putLast(char key, int value) { return map.putFirst(key, value); }
		@Override
		public boolean moveToFirst(char key) { return map.moveToLast(key); }
		@Override
		public boolean moveToLast(char key) { return map.moveToFirst(key); }
		@Override
		public int getAndMoveToFirst(char key) { return map.getAndMoveToLast(key); }
		@Override
		public int getAndMoveToLast(char key) { return map.getAndMoveToFirst(key); }
		@Override
		public char firstCharKey() { return map.lastCharKey(); }
		@Override
		public char pollFirstCharKey() { return map.pollLastCharKey(); }
		@Override
		public char lastCharKey() { return map.firstCharKey(); }
		@Override
		public char pollLastCharKey() { return map.pollFirstCharKey(); }
		@Override
		public int firstIntValue() { return map.lastIntValue(); }
		@Override
		public int lastIntValue() { return map.firstIntValue(); }
		@Override
		public Char2IntMap.Entry firstEntry() { return map.lastEntry(); }
		@Override
		public Char2IntMap.Entry lastEntry() { return map.firstEntry(); }
		@Override
		public Char2IntMap.Entry pollFirstEntry() { return map.pollLastEntry(); }
		@Override
		public Char2IntMap.Entry pollLastEntry() { return map.pollFirstEntry(); }
		@Override
		public ObjectOrderedSet<Char2IntMap.Entry> char2IntEntrySet() { return new AbstractObjectSet.ReversedObjectOrderedSet<>(map.char2IntEntrySet()); }
		@Override
		public CharOrderedSet keySet() { return new AbstractCharSet.ReversedCharOrderedSet(map.keySet()); }
		@Override
		public IntOrderedCollection values() { return map.values().reversed(); }
		@Override
		public Char2IntOrderedMap reversed() { return map; }
	}

	
	/**
	 * A Simple Type Specific Entry class to reduce boxing/unboxing
	 */
	public static class BasicEntry implements Char2IntMap.Entry {
		protected char key;
		protected int value;
		
		/**
		 * A basic Empty constructor
		 */
		public BasicEntry() {}
		/**
		 * A Boxed Constructor for supporting java variants
		 * @param key the key of a entry
		 * @param value the value of a entry
		 */
		public BasicEntry(Character key, Integer value) {
			this.key = key.charValue();
			this.value = value.intValue();
		}
		
		/**
		 * A Type Specific Constructor
		 * @param key the key of a entry
		 * @param value the value of a entry 
		 */
		public BasicEntry(char key, int value) {
			this.key = key;
			this.value = value;
		}
		
		/**
		 * A Helper method for fast replacing values
		 * @param key the key that should be replaced
		 * @param value the value that should be replaced
		 */
		public void set(char key, int value) {
			this.key = key;
			this.value = value;
		}
		
		@Override
		public char getCharKey() {
			return key;
		}

		@Override
		public int getIntValue() {
			return value;
		}

		@Override
		public int setValue(int value) {
			throw new UnsupportedOperationException();
		}
		
		@Override
		public boolean equals(Object obj) {
			if(obj instanceof Map.Entry) {
				if(obj instanceof Char2IntMap.Entry) {
					Char2IntMap.Entry entry = (Char2IntMap.Entry)obj;
					return key == entry.getCharKey() && value == entry.getIntValue();
				}
				Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj;
				Object key = entry.getKey();
				Object value = entry.getValue();
				return key instanceof Character && value instanceof Integer && this.key == ((Character)key).charValue() && this.value == ((Integer)value).intValue();
			}
			return false;
		}
		
		@Override
		public int hashCode() {
			return Character.hashCode(key) ^ Integer.hashCode(value);
		}
		
		@Override
		public String toString() {
			return Character.toString(key) + "=" + Integer.toString(value);
		}
	}
}