/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */

package net.ranides.assira.collection.maps;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import net.ranides.assira.generic.HashUtils;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BinaryOperator;
import java.util.function.Predicate;
import net.ranides.assira.collection.ACollection;
import net.ranides.assira.collection.HashFunction;
import net.ranides.assira.collection.iterators.IteratorUtils;
import net.ranides.assira.collection.sets.CustomSet;
import net.ranides.assira.collection.utils.HashCollection;
import net.ranides.assira.functional.Fold;
import net.ranides.assira.generic.CompareUtils;


public class HashMultiMap<K, V> extends AHashMap<K, V> implements MultiMap<K, V> {

    private static final long serialVersionUID = 0L;
    
    /**
     * Creates a new hash map.
     *
     * <p>The actual table size will be the least power of two greater than
     * <code>expected</code>/
     * <code>f</code>.
     *
     * @param expected the expected number of elements in the hash set.
     * @param factor the load factor.
     */
    @SuppressWarnings("unchecked")
    public HashMultiMap(int expected, float factor) {
        super(expected, factor);
    }

    /**
     * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load
     * factor.
     *
     * @param expected the expected number of elements in the hash map.
     */
    public HashMultiMap(int expected) {
        super(expected, HashCollection.LOAD_FACTOR);
    }

    /**
     * Creates a new hash map with initial expected
     * {@link Hash#DEFAULT_INITIAL_SIZE} entries and
     * {@link Hash#DEFAULT_LOAD_FACTOR} as load factor.
     */
    public HashMultiMap() {
        super(HashCollection.INITIAL_SIZE, HashCollection.LOAD_FACTOR);
    }

    /**
     * Creates a new hash map copying a given one.
     *
     * @param values a {@link Map} to be copied into the new hash map.
     * @param factor the load factor.
     */
    public HashMultiMap(Map<? extends K, ? extends V> values, float factor) {
        super(values.size(), factor);
        putAll(values);
    }

    /**
     * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load
     * factor copying a given one.
     *
     * @param values a {@link Map} to be copied into the new hash map.
     */
    public HashMultiMap(Map<? extends K, ? extends V> values) {
        this(values, HashCollection.LOAD_FACTOR);
    }

    /**
     * Creates a new hash map using the elements of two parallel arrays.
     *
     * @param keys the array of keys of the new hash map.
     * @param values the array of corresponding values in the new hash map.
     * @param factor the load factor.
     * @throws IllegalArgumentException if <code>k</code> and <code>v</code>
     * have different lengths.
     */
    public HashMultiMap(K[] keys, V values[], float factor) {
        this(keys.length, factor);
        if (keys.length != values.length) {
            throw new IllegalArgumentException("The key array and the value array have different lengths (" + keys.length + " and " + values.length + ")");
        }
        for (int i = 0; i < keys.length; i++) {
            this.put(keys[ i], values[ i]);
        }
    }
    
    /**
     * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load
     * factor using the elements of two parallel arrays.
     *
     * @param keys the array of keys of the new hash map.
     * @param values the array of corresponding values in the new hash map.
     * @throws IllegalArgumentException if <code>k</code> and <code>v</code>
     * have different lengths.
     */
    public HashMultiMap(K[] keys, V[] values) {
        this(keys, values, HashCollection.LOAD_FACTOR);
    }
    
    @Override
    protected int hash(K key) {
        return key == null ? 0x87fcd5c : HashUtils.murmurHash3(key.hashCode());
    }

    @Override    
    protected boolean compare(K key1, V value1, K key2, V value2) {
        return CompareUtils.equals(key1, key2) && CompareUtils.equals(value1, value2);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public Collection<V> getAll(Object key) {
        return new MCollection((K)key);
    }

    @SuppressWarnings("unchecked")
    @Override
    public V get(Object key, BinaryOperator<V> fold) {
        return Fold.apply(new MIterator((K)key), fold);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean containsEntry(Object key, Object value) {
        return used[ifind((K)key, (V)value)];
    }

    @SuppressWarnings("unchecked")
    @Override
    public Collection<V> removeAll(Object key) {
        List<V> list = new ArrayList<>();
        int pos;
        while(used[pos = ifind((K)key)]) {
            list.add(ishift(pos));
        }
        return list;
    }
    
    @Override
    public boolean remove(Object key, Object value) {
        int pos;
        if(used[pos = ifind((K)key, (V)value)]) {
            ishift(pos);
            return true;
        }
        return false;
    }

    @Override
    public Set<K> uniqueKeySet() {
        return new CustomSet<>(keySet(), HashFunction.produce(this::hash, this::compare));
    }
        
    private class MCollection extends ACollection<V> {
        
        private final K key;

        public MCollection(K key) {
            this.key = key;
        }

        @Override
        public Iterator<V> iterator() {
            return new MIterator(key);
        }

        @Override
        public int size() {
            return IteratorUtils.size(iterator());
        }

        @Override
        public boolean isEmpty() {
            return !iterator().hasNext();
        }
        
    }
    
    private class MIterator implements Iterator<V> {
        
        private int pos;
        private final K key;
        
        public MIterator(K key) {
            this.key = key;
            this.pos = ifind(key);
        }

        @Override
        public boolean hasNext() {
            return used[pos];
        }

        @Override
        public V next() {
            if(!used[pos]) {
                throw new NoSuchElementException();
            }
            V last = values[pos];
            do {
                pos = inext(pos);
            } while(used[pos] && !compare(key, keys[pos]));
            return last;
        }
        
    }

}
