/*
 * Copyright (c) 2015 Tento Ltd
 * 
 * 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 tentoltd.tento.testsupport.iterable;

import java.util.Iterator;

import tentoltd.tento.testsupport.data.LongSequence;

public class Iterables {

	private static final int SECOND_ELEMENT = 2;
	private static final int THIRD_ELEMENT = 3;
	private static final int FORTH_ELEMENT = 4;
	private static final int FIFTH_ELEMENT = 5;
	private static final int SIXTH_ELEMENT = 6;
	private static final int SEVENTH_ELEMENT = 7;
	private static final int EIGHT_ELEMENT = 8;
	private static final int NINTH_ELEMENT = 9;
	private static final int TENTH_ELEMENT = 10;

	public static <T> T first(Iterable<T> iterables) {
		return iterables.iterator().next();
	}

	public static <T> T second(Iterable<T> iterables) {
		return nth(iterables, SECOND_ELEMENT);
	}

	public static <T> T third(Iterable<T> iterables) {
		return nth(iterables, THIRD_ELEMENT);
	}

	public static <T> T fourth(Iterable<T> iterables) {
		return nth(iterables, FORTH_ELEMENT);
	}

	public static <T> T fifth(Iterable<T> iterables) {
		return nth(iterables, FIFTH_ELEMENT);
	}

	public static <T> T sixth(Iterable<T> iterables) {
		return nth(iterables, SIXTH_ELEMENT);
	}

	public static <T> T seventh(Iterable<T> iterables) {
		return nth(iterables, SEVENTH_ELEMENT);
	}

	public static <T> T eighth(Iterable<T> iterables) {
		return nth(iterables, EIGHT_ELEMENT);
	}

	public static <T> T ninth(Iterable<T> iterables) {
		return nth(iterables, NINTH_ELEMENT);
	}

	public static <T> T tenth(Iterable<T> iterables) {
		return nth(iterables, TENTH_ELEMENT);
	}

	public static <T> T nth(Iterable<T> iterables, int elementIndexStartingAtOne) {
		int iterableIndex = 1;
		Iterator<T> iterator = iterables.iterator();
		while (iterator.hasNext()) {
			if (iterableIndex == elementIndexStartingAtOne) {
				return iterator.next();
			}
			iterator.next();
			iterableIndex++;
		}
		return null;
	}

	private Iterables() {
		throw new Error(LongSequence.class.getName() + " should never be instantiated.");
	}
}
