package net.woodyfolsom.cs6601.p3.ngram;

import java.util.LinkedList;

public class NGram extends LinkedList<String> implements Comparable<NGram> {
	private static final long serialVersionUID = 1L;
	private int maxLength;

	public NGram(int maxLength) {
		super();
		this.maxLength = maxLength;
	}

	@Override
	public boolean add(String word) {
		if (super.size() == maxLength) {
			super.remove(0);
		}
		return super.add(word);
	}

	public int compareTo(NGram other) {
		return this.toString().compareTo(other.toString());
	}

	public NGram copy() {
		NGram nGram = new NGram(this.maxLength);
		for (String token : this) {
			nGram.add(token);
		}
		return nGram;
	}

	public NGram copy(int length) {
		if (length > super.size()) {
			throw new IllegalArgumentException();
		}

		NGram nGramCopy = new NGram(length);

		for (int i = super.size() - length; i < size(); i++) {
			nGramCopy.add(super.get(i));
		}

		return nGramCopy;
	}

	public boolean startsWith(NGram other) {
		if (other.size() != this.size() - 1) {
			return false;
		}
		for (int i = 0; i < other.size(); i++) {
			if (other.get(i).equals(this.get(i)) == false) {
				return false;
			}
		}
		return true;
	}

	public NGram subNGram(int index) {
		if (index > super.size()) {
			throw new IllegalArgumentException();
		}
		NGram subNGram = new NGram(maxLength);
		for (int i = index; i < super.size(); i++) {
			subNGram.add(super.get(i));
		}
		return subNGram;
	}

	public NGram subNGram(int start, int end) {
		if (start > end) {
			throw new IllegalArgumentException();
		}
		NGram subNGram = new NGram(end - start);
		for (int i = start; i < end; i++) {
			subNGram.add(super.get(i));
		}
		return subNGram;
	}

	@Override
	public String toString() {
		if (super.size() == 0) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < super.size() - 1; i++) {
			sb.append(super.get(i));
			sb.append(" ");
		}
		sb.append(super.get(super.size() - 1));
		return sb.toString();
	}
}