/*
 * Copyright (C) 2002-2017 Sebastiano Vigna
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package PACKAGE;

#if KEYS_REFERENCE
import it.unimi.dsi.fastutil.Stack;
#endif

import java.util.List;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collection;
import java.util.NoSuchElementException;

/**  An abstract class providing basic methods for lists implementing a type-specific list interface.
 *
 * <p>As an additional bonus, this class implements on top of the list operations a type-specific stack.
 */

public abstract class ABSTRACT_LIST KEY_GENERIC extends ABSTRACT_COLLECTION KEY_GENERIC implements LIST KEY_GENERIC, STACK KEY_GENERIC {

	protected ABSTRACT_LIST() {}

	/** Ensures that the given index is nonnegative and not greater than the list size.
	 *
	 * @param index an index.
	 * @throws IndexOutOfBoundsException if the given index is negative or greater than the list size.
	 */
	protected void ensureIndex(final int index) {
		if (index < 0)  throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
		if (index > size()) throw new IndexOutOfBoundsException("Index (" + index + ") is greater than list size (" + (size()) + ")");
	}

	/** Ensures that the given index is nonnegative and smaller than the list size.
	 *
	 * @param index an index.
	 * @throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size.
	 */
	protected void ensureRestrictedIndex(final int index) {
		if (index < 0)  throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
		if (index >= size()) throw new IndexOutOfBoundsException("Index (" + index + ") is greater than or equal to list size (" + (size()) + ")");
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation always throws an {@link UnsupportedOperationException}.
	 */
	@Override
	public void add(final int index, final KEY_GENERIC_TYPE k) {
		throw new UnsupportedOperationException();
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to the type-specific version of {@link List#add(int, Object)}.
	 */
	@Override
	public boolean add(final KEY_GENERIC_TYPE k) {
		add(size(), k);
		return true;
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation always throws an {@link UnsupportedOperationException}.
	 */
	@Override
	public KEY_GENERIC_TYPE REMOVE_KEY(final int i) {
		throw new UnsupportedOperationException();
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation always throws an {@link UnsupportedOperationException}.
	 */
	@Override
	public KEY_GENERIC_TYPE set(final int index, final KEY_GENERIC_TYPE k) {
		throw new UnsupportedOperationException();
	}

	/** Adds all of the elements in the specified collection to this list (optional operation). */
	@Override
	public boolean addAll(int index, final Collection<? extends KEY_GENERIC_CLASS> c) {
		ensureIndex(index);
		final Iterator<? extends KEY_GENERIC_CLASS> i = c.iterator();
		final boolean retVal = i.hasNext();
		while(i.hasNext()) add(index++, KEY_CLASS2TYPE(i.next()));
		return retVal;
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to the type-specific version of {@link List#addAll(int, Collection)}.
	 */
	@Override
	public boolean addAll(final Collection<? extends KEY_GENERIC_CLASS> c) {
		return addAll(size(), c);
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to {@link #listIterator()}.
	 */
	@Override
	public KEY_LIST_ITERATOR KEY_GENERIC iterator() {
		return listIterator();
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to {@link #listIterator(int) listIterator(0)}.
	 */
	@Override
	public KEY_LIST_ITERATOR KEY_GENERIC listIterator() {
		return listIterator(0);
	}

	/** {@inheritDoc}
	 * <p>This implementation is based on the random-access methods. */
	@Override
	public KEY_LIST_ITERATOR KEY_GENERIC listIterator(final int index) {
		ensureIndex(index);

		return new KEY_LIST_ITERATOR KEY_GENERIC() {
				int pos = index, last = -1;

				@Override
				public boolean hasNext() { return pos < ABSTRACT_LIST.this.size(); }
				@Override
				public boolean hasPrevious() { return pos > 0; }
				@Override
				public KEY_GENERIC_TYPE NEXT_KEY() { if (! hasNext()) throw new NoSuchElementException(); return ABSTRACT_LIST.this.GET_KEY(last = pos++); }
				@Override
				public KEY_GENERIC_TYPE PREV_KEY() { if (! hasPrevious()) throw new NoSuchElementException(); return ABSTRACT_LIST.this.GET_KEY(last = --pos); }
				@Override
				public int nextIndex() { return pos; }
				@Override
				public int previousIndex() { return pos - 1; }
				@Override
				public void add(final KEY_GENERIC_TYPE k) {
					ABSTRACT_LIST.this.add(pos++, k);
					last = -1;
				}
				@Override
				public void set(final KEY_GENERIC_TYPE k) {
					if (last == -1) throw new IllegalStateException();
					ABSTRACT_LIST.this.set(last, k);
				}
				@Override
				public void remove() {
					if (last == -1) throw new IllegalStateException();
					ABSTRACT_LIST.this.REMOVE_KEY(last);
					/* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */
					if (last < pos) pos--;
					last = -1;
				}
			};
	}

	/** Returns true if this list contains the specified element.
	 * <p>This implementation delegates to {@code indexOf()}.
	 * @see List#contains(Object)
	 */

	@Override
	public boolean contains(final KEY_TYPE k) {
		return indexOf(k) >= 0;
	}

	@Override
	public int indexOf(final KEY_TYPE k) {
		final KEY_LIST_ITERATOR KEY_GENERIC i = listIterator();
		KEY_GENERIC_TYPE e;
		while(i.hasNext()) {
			e = i.NEXT_KEY();
			if (KEY_EQUALS(k, e)) return i.previousIndex();
		}
		return -1;
	}

	@Override
	public int lastIndexOf(final KEY_TYPE k) {
		KEY_LIST_ITERATOR KEY_GENERIC i = listIterator(size());
		KEY_GENERIC_TYPE e;
		while(i.hasPrevious()) {
			e = i.PREV_KEY();
			if (KEY_EQUALS(k, e)) return i.nextIndex();
		}
		return -1;
	}

	@Override
	public void size(final int size) {
		int i = size();
		if (size > i) while(i++ < size) add(KEY_NULL);
		else while(i-- != size) REMOVE_KEY(i);
	}


	@Override
	public LIST KEY_GENERIC subList(final int from, final int to) {
		ensureIndex(from);
		ensureIndex(to);
		if (from > to) throw new IndexOutOfBoundsException("Start index (" + from + ") is greater than end index (" + to + ")");

		return new SUBLIST KEY_GENERIC_DIAMOND(this, from, to);
	}

	/** {@inheritDoc}
	 *
	 * <p>This is a trivial iterator-based implementation. It is expected that
	 * implementations will override this method with a more optimized version.
	 */
	@Override
	public void removeElements(final int from, final int to) {
		ensureIndex(to);
		KEY_LIST_ITERATOR KEY_GENERIC i = listIterator(from);
		int n = to - from;
		if (n < 0) throw new IllegalArgumentException("Start index (" + from + ") is greater than end index (" + to + ")");
		while(n-- != 0) {
			i.NEXT_KEY();
			i.remove();
		}
	}

	/** {@inheritDoc}
	 *
	 * <p>This is a trivial iterator-based implementation. It is expected that
	 * implementations will override this method with a more optimized version.
	 */
	@Override
	public void addElements(int index, final KEY_GENERIC_TYPE a[], int offset, int length) {
		ensureIndex(index);
		if (offset < 0) throw new ArrayIndexOutOfBoundsException("Offset (" + offset + ") is negative");
		if (offset + length > a.length) throw new ArrayIndexOutOfBoundsException("End index (" + (offset + length) + ") is greater than array length (" + a.length + ")");
		while(length-- != 0) add(index++, a[offset++]);
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to the analogous method for array fragments.
	 */
	@Override
	public void addElements(final int index, final KEY_GENERIC_TYPE a[]) {
		addElements(index, a, 0, a.length);
	}

	/** {@inheritDoc}
	 *
	 * <p>This is a trivial iterator-based implementation. It is expected that
	 * implementations will override this method with a more optimized version.
	 */
	@Override
	public void getElements(final int from, final KEY_TYPE a[], int offset, int length) {
		KEY_LIST_ITERATOR KEY_GENERIC i = listIterator(from);
		if (offset < 0) throw new ArrayIndexOutOfBoundsException("Offset (" + offset + ") is negative");
		if (offset + length > a.length) throw new ArrayIndexOutOfBoundsException("End index (" + (offset + length) + ") is greater than array length (" + a.length + ")");
		if (from + length > size()) throw new IndexOutOfBoundsException("End index (" + (from + length) + ") is greater than list size (" + size() + ")");
		while(length-- != 0) a[offset++] = i.NEXT_KEY();
	}

	/** {@inheritDoc}
	 * <p>This implementation delegates to {@link #removeElements(int, int)}.*/
	@Override
	public void clear() {
		removeElements(0, size());
	}


#if ! KEY_CLASS_Reference
	private boolean valEquals(final Object a, final Object b) {
		return a == null ? b == null : a.equals(b);
	}
#endif

	/** Returns the hash code for this list, which is identical to {@link java.util.List#hashCode()}.
	 *
	 * @return the hash code for this list.
	 */
	@Override
	public int hashCode() {
		KEY_ITERATOR KEY_GENERIC i = iterator();
		int h = 1, s = size();
		while (s-- != 0) {
			KEY_GENERIC_TYPE k = i.NEXT_KEY();
			h = 31 * h + KEY2JAVAHASH(k);
		}
		return h;
	}


	@Override
	public boolean equals(final Object o) {
		if (o == this) return true;
		if (! (o instanceof List)) return false;

		final List<?> l = (List<?>)o;
		int s = size();
		if (s != l.size()) return false;

#if KEYS_PRIMITIVE
		if (l instanceof LIST) {
			final KEY_LIST_ITERATOR KEY_GENERIC i1 = listIterator(), i2 = ((LIST KEY_GENERIC)l).listIterator();
			while(s-- != 0) if (i1.NEXT_KEY() != i2.NEXT_KEY()) return false;
			return true;
		}
#endif

		final ListIterator<?> i1 = listIterator(), i2 = l.listIterator();

#if KEY_CLASS_Reference
		while(s-- !=  0) if (i1.next() != i2.next()) return false;
#else
		while(s-- !=  0) if (! valEquals(i1.next(), i2.next())) return false;
#endif
		return true;
	}

#if ! KEY_CLASS_Reference
	/** Compares this list to another object. If the
	 * argument is a {@link java.util.List}, this method performs a lexicographical comparison; otherwise,
	 * it throws a {@code ClassCastException}.
	 *
	 * @param l a list.
	 * @return if the argument is a {@link java.util.List}, a negative integer,
	 * zero, or a positive integer as this list is lexicographically less than, equal
	 * to, or greater than the argument.
	 * @throws ClassCastException if the argument is not a list.
	 */

	SUPPRESS_WARNINGS_KEY_UNCHECKED
	@Override
	public int compareTo(final List<? extends KEY_GENERIC_CLASS> l) {
		if (l == this) return 0;

		if (l instanceof LIST) {

			final KEY_LIST_ITERATOR KEY_GENERIC i1 = listIterator(), i2 = ((LIST KEY_GENERIC)l).listIterator();
			int r;
			KEY_GENERIC_TYPE e1, e2;

			while(i1.hasNext() && i2.hasNext()) {
				e1 = i1.NEXT_KEY();
				e2 = i2.NEXT_KEY();
				if ((r = KEY_CMP(e1, e2)) != 0) return r;
			}
			return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0);
		}

		ListIterator<? extends KEY_GENERIC_CLASS> i1 = listIterator(), i2 = l.listIterator();
		int r;

		while(i1.hasNext() && i2.hasNext()) {
			if ((r = ((Comparable<? super KEY_GENERIC_CLASS>)i1.next()).compareTo(i2.next())) != 0) return r;
		}
		return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0);
	}
#endif

	@Override
	public void push(final KEY_GENERIC_TYPE o) {
		add(o);
	}

	@Override
	public KEY_GENERIC_TYPE POP() {
		if (isEmpty()) throw new NoSuchElementException();
		return REMOVE_KEY(size() - 1);
	}

	@Override
	public KEY_GENERIC_TYPE TOP() {
		if (isEmpty()) throw new NoSuchElementException();
		return GET_KEY(size() - 1);
	}

	@Override
	public KEY_GENERIC_TYPE PEEK(final int i) {
		return GET_KEY(size() - 1 - i);
	}

#if KEYS_PRIMITIVE

	/** Removes a single instance of the specified element from this collection, if it is present (optional operation).
	 * <p>This implementation delegates to {@code indexOf()}.
	 * @see List#remove(Object)
	 */
	@Override
	public boolean rem(final KEY_TYPE k) {
		int index = indexOf(k);
		if (index == -1) return false;
		REMOVE_KEY(index);
		return true;
	}

	@Override
	public boolean addAll(int index, final COLLECTION c) {
		ensureIndex(index);
		final KEY_ITERATOR i = c.iterator();
		final boolean retVal = i.hasNext();
		while(i.hasNext()) add(index++, i.NEXT_KEY());
		return retVal;
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to the type-specific version of {@link List#addAll(int, Collection)}.
	 */
	@Override
	public boolean addAll(final int index, final LIST l) {
		return addAll(index, (COLLECTION)l);
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to the type-specific version of {@link List#addAll(int, Collection)}.
	 */
	@Override
	public boolean addAll(final COLLECTION c) {
		return addAll(size(), c);
	}

	/** {@inheritDoc}
	 *
	 * <p>This implementation delegates to the type-specific list version of {@link List#addAll(int, Collection)}.
	 */
	@Override
	public boolean addAll(final LIST l) {
		return addAll(size(), l);
	}

#endif

	@Override
	public String toString() {
		final StringBuilder s = new StringBuilder();
		final KEY_ITERATOR KEY_GENERIC i = iterator();
		int n = size();
		KEY_GENERIC_TYPE k;
		boolean first = true;

		s.append("[");

		while(n-- != 0) {
			if (first) first = false;
			else s.append(", ");
			k = i.NEXT_KEY();
#if KEYS_REFERENCE
			if (this == k) s.append("(this list)"); else
#endif
				s.append(String.valueOf(k));
		}

		s.append("]");
		return s.toString();
	}

	/** A class implementing a sublist view. */
	public static class SUBLIST KEY_GENERIC extends ABSTRACT_LIST KEY_GENERIC implements java.io.Serializable {
		private static final long serialVersionUID = -7046029254386353129L;
		/** The list this sublist restricts. */
		protected final LIST KEY_GENERIC l;
		/** Initial (inclusive) index of this sublist. */
		protected final int from;
		/** Final (exclusive) index of this sublist. */
		protected int to;

		public SUBLIST(final LIST KEY_GENERIC l, final int from, final int to) {
			this.l = l;
			this.from = from;
			this.to = to;
		}

		private boolean assertRange() {
			assert from <= l.size();
			assert to <= l.size();
			assert to >= from;
			return true;
		}

		@Override
		public boolean add(final KEY_GENERIC_TYPE k) {
			l.add(to, k);
			to++;
			assert assertRange();
			return true;
		}

		@Override
		public void add(final int index, final KEY_GENERIC_TYPE k) {
			ensureIndex(index);
			l.add(from + index, k);
			to++;
			assert assertRange();
		}

		@Override
		public boolean addAll(final int index, final Collection<? extends KEY_GENERIC_CLASS> c) {
			ensureIndex(index);
			to += c.size();
			return l.addAll(from + index, c);
		}

		@Override
		public KEY_GENERIC_TYPE GET_KEY(final int index) {
			ensureRestrictedIndex(index);
			return l.GET_KEY(from + index);
		}

		@Override
		public KEY_GENERIC_TYPE REMOVE_KEY(final int index) {
			ensureRestrictedIndex(index);
			to--;
			return l.REMOVE_KEY(from + index);
		}

		@Override
		public KEY_GENERIC_TYPE set(final int index, final KEY_GENERIC_TYPE k) {
			ensureRestrictedIndex(index);
			return l.set(from + index, k);
		}

		@Override
		public int size() {
			return to - from;
		}

		@Override
		public void getElements(final int from, final KEY_TYPE[] a, final int offset, final int length) {
			ensureIndex(from);
			if (from + length > size())  throw new IndexOutOfBoundsException("End index (" + from + length + ") is greater than list size (" + size() + ")");
			l.getElements(this.from + from, a, offset, length);
		}

		@Override
		public void removeElements(final int from, final int to) {
			ensureIndex(from);
			ensureIndex(to);
			l.removeElements(this.from + from, this.from + to);
			this.to -= (to - from);
			assert assertRange();
		}

		@Override
		public void addElements(int index, final KEY_GENERIC_TYPE a[], int offset, int length) {
			ensureIndex(index);
			l.addElements(this.from + index, a, offset, length);
			this.to += length;
			assert assertRange();
		}

		@Override
		public KEY_LIST_ITERATOR KEY_GENERIC listIterator(final int index) {
			ensureIndex(index);

			return new KEY_LIST_ITERATOR KEY_GENERIC() {
					int pos = index, last = -1;

					@Override
					public boolean hasNext() { return pos < size(); }
					@Override
					public boolean hasPrevious() { return pos > 0; }
					@Override
					public KEY_GENERIC_TYPE NEXT_KEY() { if (! hasNext()) throw new NoSuchElementException(); return l.GET_KEY(from + (last = pos++)); }
					@Override
					public KEY_GENERIC_TYPE PREV_KEY() { if (! hasPrevious()) throw new NoSuchElementException(); return l.GET_KEY(from + (last = --pos)); }
					@Override
					public int nextIndex() { return pos; }
					@Override
					public int previousIndex() { return pos - 1; }
					@Override
					public void add(KEY_GENERIC_TYPE k) {
						if (last == -1) throw new IllegalStateException();
						SUBLIST.this.add(pos++, k);
						last = -1;
						assert assertRange();
					}
					@Override
					public void set(KEY_GENERIC_TYPE k) {
						if (last == -1) throw new IllegalStateException();
						SUBLIST.this.set(last, k);
					}
					@Override
					public void remove() {
						if (last == -1) throw new IllegalStateException();
						SUBLIST.this.REMOVE_KEY(last);
						/* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */
						if (last < pos) pos--;
						last = -1;
						assert assertRange();
					}
				};
		}

		@Override
		public LIST KEY_GENERIC subList(final int from, final int to) {
			ensureIndex(from);
			ensureIndex(to);
			if (from > to) throw new IllegalArgumentException("Start index (" + from + ") is greater than end index (" + to + ")");

			return new SUBLIST KEY_GENERIC_DIAMOND(this, from, to);
		}

#if KEYS_PRIMITIVE

		@Override
		public boolean rem(final KEY_TYPE k) {
			int index = indexOf(k);
			if (index == -1) return false;
			to--;
			l.REMOVE_KEY(from + index);
			assert assertRange();
			return true;
		}

		@Override
		public boolean addAll(final int index, final COLLECTION c) {
			ensureIndex(index);
			return super.addAll(index, c);
		}

		@Override
		public boolean addAll(final int index, final LIST l) {
			ensureIndex(index);
			return super.addAll(index, l);
		}
#endif

	}

}
