/*******************************************************************************
 * Copyright (c) 2015-2020 The University of York, Aston University.
 * 
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the Eclipse
 * Public License, v. 2.0 are satisfied: GNU General Public License, version 3.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-3.0
 *
 * Contributors:
 *     Antonio Garcia-Dominguez - initial API and implementation
 ******************************************************************************/
package org.eclipse.hawk.orientdb.indexes;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import org.eclipse.hawk.core.graph.IGraphIterable;

import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.index.OCompositeKey;
import com.orientechnologies.orient.core.index.OIndex;

final class ResultSetIterable<T> implements IGraphIterable<T> {
	private final Class<T> klass;
	private final String key;
	private final Object valueExpr;
	private final OrientNodeIndex nodeIndex;

	public ResultSetIterable(String key, Object valueExpr, OrientNodeIndex nodeIndex, Class<T> klass) {
		this.key = key;
		this.valueExpr = valueExpr;
		this.klass = klass;
		this.nodeIndex = nodeIndex;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Iterator<T> iterator() {
		final OIndex<?> idx = nodeIndex.getIndex(valueExpr.getClass());
		if (idx == null) {
			return Collections.emptyIterator();
		}

		final Collection<OIdentifiable> resultSet = (Collection<OIdentifiable>) idx.get(new OCompositeKey(key, valueExpr));
		if (resultSet == null || resultSet.isEmpty()) {
			return Collections.emptyListIterator();
		} else {
			final Iterator<OIdentifiable> itIdentifiable = resultSet.iterator();
			return new Iterator<T>() {
				@Override
				public boolean hasNext() {
					return itIdentifiable.hasNext();
				}

				@Override
				public T next() {
					return nodeIndex.getDatabase().getElementById(itIdentifiable.next().getIdentity(), klass);
				}

				@Override
				public void remove() {
					itIdentifiable.remove();
				}
			};
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public int size() {
		final OIndex<?> idx = nodeIndex.getIndex(valueExpr.getClass());
		if (idx == null) {
			return 0;
		}

		final Collection<OIdentifiable> resultSet =
			(Collection<OIdentifiable>) idx.get(new OCompositeKey(key, valueExpr));
		return resultSet.size();
	}

	@Override
	public T getSingle() {
		return iterator().next();
	}
}