package editor.wordcount;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayWordCounter implements WordCounter {
	private ArrayList<WordCounterEntry> words = new ArrayList<>();

	@Override
	public WordCounter makeCopy() {
		ArrayWordCounter copy = new ArrayWordCounter();
		this.copyInto(copy);
		return copy;
	}
	
	private WordCounterEntry find(String word) {
		for (WordCounterEntry entry: words) {
			if (entry.getWord().equals(word)) {
				return entry;
			}
		}
		return null;
	}

	@Override
	public int get(String word) {
		WordCounterEntry entry = find(word);
		return entry == null ? 0 : entry.getCount();
	}

	@Override
	public void bump(String word) {
		WordCounterEntry entry = find(word);
		if (entry == null) {
			words.add(new WordCounterEntry(word, 1));
		} else {
			entry.bump();
		}
	}

	@Override
	public void dock(String word) {
		WordCounterEntry entry = find(word);
		if (entry != null) entry.dock();
	}

	@Override
	public Iterator<WordCounterEntry> iterator() {
		return words.iterator();
	}

	@Override
	public boolean isConsistent() {
		return true;
	}

}
