/*
 * @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.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 *
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public class LazyMap<K, V> extends AMap<K, V> {
    
    private final Map<K, V> data;
    
    private final Function<? super K, ? extends V> function;

    public LazyMap(Map<K, V> data, Supplier<? extends V> supplier) {
        this(data, (Function<K, V> & Serializable) $0 -> supplier.get());
    }
    
    public LazyMap(Map<K, V> data, Function<? super K, ? extends V> function) {
        this.data = data;
        this.function = function;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return data.entrySet();
    }

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

    @Override
    public boolean containsKey(Object key) {
        return data.containsKey(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return data.containsValue(value);
    }
    
    @SuppressWarnings("element-type-mismatch")
    public V getIfPresent(Object key) {
        return data.containsKey(key) ? data.get(key) : null;
    }

    @Override
    @SuppressWarnings(value = {"element-type-mismatch", "unchecked"})
    public V get(Object key) {
        V ret = data.get(key);
        if (null == ret && !data.containsKey(key)) {
            data.put((K) key, ret = function.apply((K) key));
        }
        return ret;
    }

    @Override
    public void clear() {
        data.clear();
    }

    @Override
    public V remove(Object key) {
        return data.remove(key);
    }
    
    @Override
    public boolean remove(Object key, Object value) {
        return data.remove(key, value);
    }

    @Override
    public V put(K key, V value) {
        return data.put(key, value);
    }
    
}
