package sample.entity;

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

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import appengine.util.TestUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

import static org.junit.Assert.assertThat;

public class SampleEntity1Test {
	@BeforeClass
	public static void setUpBeforeClass() {
		Logger.getLogger("DataNucleus.Plugin").setLevel(Level.OFF);
	}

	@Before
	public void setUp() {
		TestUtil.setUpAppEngine("target/test", true);
		TestUtil.delegateToTraceLowLevel();
	}

	@After
	public void tearDown() {
		TestUtil.restoreDelegateFromTraceLowLevel();
		TestUtil.tearDownAppEngine();
	}

	@Test
	public void jdo() {
		PersistenceManager manager = PMF.get().getPersistenceManager();
		SampleEntity1 entity1 = new SampleEntity1();
		entity1.setValue("value1");
		SampleEntity1 entity2 = new SampleEntity1();
		entity2.setValue("value2");
		manager.makePersistentAll(entity1, entity2);
		manager.close();

		manager = PMF.get().getPersistenceManager();
		Query query = manager.newQuery(SampleEntity1.class);
		query.setResult("count(this)");
		int count = (Integer) query.execute();
		assertThat(count, is(equalTo(2)));
		manager.close();
	}

	@Test
	public void lowLevelApi() {
		final String KIND = SampleEntity1.class.getSimpleName();
		Entity entity1 = new Entity(KIND);
		entity1.setProperty("value", "value1");
		Entity entity2 = new Entity(KIND);
		entity2.setProperty("value", "value2");
		DatastoreService service = DatastoreServiceFactory
				.getDatastoreService();
		service.put(entity1);
		service.put(entity2);

		int count = service.prepare(
				new com.google.appengine.api.datastore.Query(KIND))
				.countEntities();
		assertThat(count, is(equalTo(2)));
	}
}
