package de.accso.flexinale.common.shared_kernel;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

// needed as one cannot derive from Collections.synchronizedSet()'s result type (as package-protected, sigh)
class SynchronizedSet<T> implements Set<T> {

    private final Set<T> backingSet = new HashSet<T>();
    private final Object lock = new Object();

    @Override
    public boolean add(T object) {
        synchronized (lock) {
            return backingSet.add(object);
        }
    }

    @Override
    public boolean addAll(Collection<? extends T> collection) {
        synchronized (lock) {
            return backingSet.addAll(collection);
        }
    }

    @Override
    public void clear() {
        synchronized (lock) {
            backingSet.clear();
        }
    }

    @Override
    public boolean contains(Object object) {
        synchronized (lock) {
            return backingSet.contains(object);
        }
    }

    @Override
    public boolean containsAll(Collection<?> collection) {
        synchronized (lock) {
            return backingSet.containsAll(collection);
        }
    }

    @Override
    public boolean isEmpty() {
        synchronized (lock) {
            return backingSet.isEmpty();
        }
    }

    // needs to get synchronized outside!
    @Override
    public Iterator<T> iterator() {
        return backingSet.iterator();
    }

    @Override
    public T[] toArray() {
        synchronized (lock) {
            return (T[]) backingSet.toArray();
        }
    }

    @Override
    public T[] toArray(Object[] object) {
        synchronized (lock) {
            return (T[]) backingSet.toArray(object);
        }
    }

    @Override
    public boolean remove(Object object) {
        synchronized (lock) {
            return backingSet.remove(object);
        }
    }

    @Override
    public boolean removeAll(Collection<?> collection) {
        synchronized (lock) {
            return backingSet.removeAll(collection);
        }
    }

    @Override
    public boolean retainAll(Collection<?> collection) {
        synchronized (lock) {
            return backingSet.retainAll(collection);
        }
    }

    @Override
    public int size() {
        synchronized (lock) {
            return backingSet.size();
        }
    }

    @Override
    public boolean equals(Object object) {
        synchronized (lock) {
            if (object == this) {
                return true;
            }
            return backingSet.equals(object);
        }
    }

    @Override
    public int hashCode() {
        synchronized (lock) {
            return backingSet.hashCode();
        }
    }

    @Override
    public String toString() {
        synchronized (lock) {
            return backingSet.toString();
        }
    }
}