package appengine.util;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.Test;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

/**
 * 1000件を超える結果が返るクエリの実行を試す。
 * <p>デプロイ環境でParentというKind名で大量のデータが存在している事が前提。</p>
 * <p>ローカル環境では何も実行しない。</p>
 * @author shin1ogawa
 */
public class LargeResultSetTest {

	final static Logger logger = Logger.getLogger(LargeResultSetTest.class.getName());


	/**
	 * 1000件以上返される条件でのcountEntities()
	 */
	@Test
	public void countEntities() {
		if (AppEngineUtil.isLocalDevelopment()) {
			return;
		}
		Query query =
				new Query("Person")
					.addFilter("height", FilterOperator.GREATER_THAN_OR_EQUAL, 120.0);
		int countEntities =
				DatastoreServiceFactory.getDatastoreService().prepare(query).countEntities();
		logger.log(Level.INFO, "countEntities=" + countEntities);
	}

	/**
	 * 5000件の制限付きで{@link PreparedQuery#asList(FetchOptions)}する。
	 */
	@Test
	public void asList5000() {
		if (AppEngineUtil.isLocalDevelopment()) {
			return;
		}
		Query query =
				new Query("Person")
					.addFilter("height", FilterOperator.GREATER_THAN_OR_EQUAL, 120.0);

		List<Entity> asList =
				DatastoreServiceFactory.getDatastoreService().prepare(query).asList(
						FetchOptions.Builder.withOffset(0).limit(5000));
		logger.log(Level.INFO, "countEntities=" + asList.size());
	}

	/**
	 * 5000件の制限付きで{@link PreparedQuery#asList(FetchOptions)}する。
	 */
	@Test
	public void asList5000KeysOnly() {
		if (AppEngineUtil.isLocalDevelopment()) {
			return;
		}
		Query query =
				new Query("Person")
					.addFilter("height", FilterOperator.GREATER_THAN_OR_EQUAL, 120.0);

		List<Entity> asList =
				DatastoreServiceFactory.getDatastoreService().prepare(query.setKeysOnly()).asList(
						FetchOptions.Builder.withOffset(0).limit(5000));
		logger.log(Level.INFO, "countEntities=" + asList.size());
	}
}
