package abstraction;

import datastructures.set.CustomSet;
import datastructures.set.CustomStrictSet;

import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * A Decorator to intercept all state changes on a set and sync them with the persistence layer of the
 * application.
 *
 * @param <T> The data type that should be stored and updated in the persistence layer
 */
public class CustomSetPersistenceDecorator<T> implements CustomSet<T> {

	private final CustomSet<T> set;
	private final PersistenceAdapter<T> persistenceAdapter;

	public CustomSetPersistenceDecorator(PersistenceAdapter<T> persistenceAdapter) {
		this.persistenceAdapter = persistenceAdapter;
		this.set = new CustomStrictSet(persistenceAdapter.getAll());
	}

	@Override
	public Optional<T> find(Predicate<T> predicate) {
		return set.find(predicate);
	}

	@Override
	public Stream<T> stream() {
		return set.stream();
	}

	@Override
	public boolean add(T value) {
		persistenceAdapter.add(value);
		return set.add(value);
	}

	@Override
	public boolean remove(T value) {
		persistenceAdapter.remove(value);
		return this.set.remove(value);
	}

	@Override
	public Set<T> getSet() {
		return this.set.getSet();
	}

}
