package tag;

import datastructures.set.CustomSet;
import abstraction.CustomSetPersistenceDecorator;
import abstraction.PersistenceAdapter;
import exeptions.TagMatcherAlreadyExists;
import tag.matcherImplementations.CustomTagMatcher;

import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;

public class TagMatcherRepository {

	final Set<TagMatcher> staticTagMatchers;

	final private CustomSet<CustomTagMatcher> customTagMatchers;

	public TagMatcherRepository(final PersistenceAdapter<CustomTagMatcher> customTagMatcherPersistenceAdapter,
	                            final Set<TagMatcher> staticTagMatchers) {
		this.staticTagMatchers = staticTagMatchers;
		this.customTagMatchers =
				new CustomSetPersistenceDecorator<CustomTagMatcher>(customTagMatcherPersistenceAdapter);
	}

	public Set<TagMatcher> getTagMatchers() {
		var set = new HashSet<TagMatcher>(staticTagMatchers);
		set.addAll(customTagMatchers.getSet());
		return set;
	}

	public void addCustomTagMatcher(CustomTagMatcher customTagMatcher) {
		checkDuplicates(customTagMatcher);

		customTagMatchers.add(customTagMatcher);
	}

	private void checkDuplicates(CustomTagMatcher customTagMatcher) {
		Predicate<TagMatcher> predicate = matcher -> (matcher.tagName.equals(customTagMatcher.getTagName()));
		var alreadyExists = staticTagMatchers.stream().anyMatch(predicate) || customTagMatchers
				.getSet()
				.stream()
				.anyMatch(predicate);

		if (alreadyExists) {
			throw new TagMatcherAlreadyExists(customTagMatcher.tagName);
		}
	}
}
