package appengine.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;

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

import static org.junit.Assert.assertThat;

/**
 * @author shin1ogawa
 */
public class LocalDataFileUtilTest {

	/**
	 * {@link LocalDataFileUtil#getKinds(String)}
	 */
	@Test
	public void getKinds() {
		String[] kinds = LocalDataFileUtil.getKinds("gae-j-sandbox");
		assertThat(kinds.length, is(equalTo(2)));
		assertThat(kinds, hasItemInArray(containsString("Kind1")));
		assertThat(kinds, hasItemInArray(containsString("Kind2")));
	}

	/**
	 * ファイルへの保存なしモードで準備。
	 * @throws IOException 
	 */
	@Before
	public void setUp() throws IOException {
		if (AppEngineUtil.isLocalDevelopment()) {
			TestUtil.setUpAppEngine("gae-j-sandbox", "gae-j-sandbox.1",
					"target/LocalDataFileUtilTest", true);
		}
		createSampleEntities(DatastoreServiceFactory.getDatastoreService());
	}

	/**
	 * 終了.
	 */
	@After
	public void tearDown() {
		if (AppEngineUtil.isLocalDevelopment()) {
			TestUtil.tearDownAppEngine();
		}
	}

	private void createSampleEntities(DatastoreService service) {
		Entity entity1 = new Entity("Kind1");
		entity1.setProperty("property1", Long.valueOf(1L));
		entity1.setProperty("property2", Integer.valueOf(2));
		entity1.setProperty("property3", "property3-value");
		entity1.setUnindexedProperty("property4", new Text("property4-value"));
		entity1.setUnindexedProperty("property5", new Blob("property5-value".getBytes()));
		Key entity1Key = service.put(entity1);
		Entity entity2 = new Entity("Kind2");
		entity2.setProperty("entity-key", entity1Key);
		entity2.setUnindexedProperty("entity-body", new Blob(getBytes(entity1)));
		service.put(entity2);
	}

	static byte[] getBytes(Entity entity) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream os = null;
		try {
			os = new ObjectOutputStream(bos);
			os.writeObject(entity);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(os);
		}
		return bos.toByteArray();
	}
}
