package org.xbib.logging.util;

import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public final class CopyOnWriteMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Cloneable {

    private volatile FastCopyHashMap<K, V> map = new FastCopyHashMap<>(32, 0.25f);

    @SuppressWarnings("rawtypes")
    private static final AtomicReferenceFieldUpdater<CopyOnWriteMap, FastCopyHashMap> mapUpdater =
            AtomicReferenceFieldUpdater.newUpdater(CopyOnWriteMap.class, FastCopyHashMap.class, "map");

    public CopyOnWriteMap() {
        super();
    }

    @Override
    public V get(final Object key) {
        return map.get(key);
    }

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

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

    @Override
    public boolean containsValue(final Object value) {
        return map.containsValue(value);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void clear() {
        map = new FastCopyHashMap<>(32, 0.25f);
    }

    @Override
    public V put(final K key, final V value) {
        FastCopyHashMap<K, V> oldVal, newVal;
        V result;
        do {
            oldVal = map;
            newVal = oldVal.clone();
            result = newVal.put(key, value);
        } while (!mapUpdater.compareAndSet(this, oldVal, newVal));
        return result;
    }

    @Override
    public V remove(final Object key) {
        FastCopyHashMap<K, V> oldVal, newVal;
        V result;
        do {
            oldVal = map;
            if (!oldVal.containsKey(key)) {
                return null;
            }
            newVal = oldVal.clone();
            result = newVal.remove(key);
        } while (!mapUpdater.compareAndSet(this, oldVal, newVal));
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    public CopyOnWriteMap<K, V> clone() {
        try {
            return (CopyOnWriteMap<K, V>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public V putIfAbsent(final K key, final V value) {
        FastCopyHashMap<K, V> oldVal, newVal;
        do {
            oldVal = map;
            if (oldVal.containsKey(key)) {
                return oldVal.get(key);
            }
            newVal = oldVal.clone();
            newVal.put(key, value);
        } while (!mapUpdater.compareAndSet(this, oldVal, newVal));
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean remove(final Object key, final Object value) {
        FastCopyHashMap<K, V> oldVal, newVal;
        do {
            oldVal = map;
            if (value == oldVal.get(key) && (value != null || oldVal.containsKey(key))) {
                if (oldVal.size() == 1) {
                    newVal = new FastCopyHashMap<>(32, 0.25f);
                } else {
                    newVal = oldVal.clone();
                    newVal.remove(key);
                }
            } else {
                return false;
            }
        } while (!mapUpdater.compareAndSet(this, oldVal, newVal));
        return true;
    }

    @Override
    public boolean replace(final K key, final V oldValue, final V newValue) {
        FastCopyHashMap<K, V> oldVal, newVal;
        do {
            oldVal = map;
            if (oldValue == oldVal.get(key) && (oldValue != null || oldVal.containsKey(key))) {
                newVal = oldVal.clone();
                newVal.put(key, newValue);
            } else {
                return false;
            }
        } while (!mapUpdater.compareAndSet(this, oldVal, newVal));
        return true;
    }

    @Override
    public V replace(final K key, final V value) {
        FastCopyHashMap<K, V> oldVal, newVal;
        V result;
        do {
            oldVal = map;
            if (value == oldVal.get(key) && (value != null || oldVal.containsKey(key))) {
                newVal = oldVal.clone();
                result = newVal.put(key, value);
            } else {
                return null;
            }
        } while (!mapUpdater.compareAndSet(this, oldVal, newVal));
        return result;
    }

    @Override
    public Set<K> keySet() {
        return Collections.unmodifiableSet(map.keySet());
    }

    @Override
    public Collection<V> values() {
        return Collections.unmodifiableCollection(map.values());
    }

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