package com.shin1ogawa.service;

import static org.junit.Assert.assertEquals;

import java.io.File;

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

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.dev.LocalDatastoreService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.development.ApiProxyLocalImpl;
import com.google.apphosting.api.ApiProxy;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Scopes;
import com.shin1ogawa.JdoModule;
import com.shin1ogawa.entity.Messages;

public class MessagesServiceTest {

	private static Injector injector;


	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		injector = Guice.createInjector(new AbstractModule() {

			@Override
			protected void configure() {
				install(new JdoModule());
				bind(IMessagesService.class).to(MessagesService.class).in(Scopes.SINGLETON);
			}
		});
	}

	@Before
	public void setUp() {
		ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment());
		ApiProxy.setDelegate(new ApiProxyLocalImpl(new File("target/testDataStore")) {
		});
		ApiProxyLocalImpl proxy = (ApiProxyLocalImpl) ApiProxy.getDelegate();
		proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY, Boolean.TRUE.toString());
	}

	@After
	public void tearDown() {
		ApiProxyLocalImpl proxy = (ApiProxyLocalImpl) ApiProxy.getDelegate();
		LocalDatastoreService datastoreService =
				(LocalDatastoreService) proxy.getService("datastore_v3");
		datastoreService.clearProfiles();
		ApiProxy.setDelegate(null);
		ApiProxy.setEnvironmentForCurrentThread(null);
	}

	@Test
	public void testNewMessage01() {
		IMessagesService service = injector.getInstance(IMessagesService.class);
		service.newMessage(UserServiceFactory.getUserService().getCurrentUser(), "abcde");
		Query query = new Query(Messages.class.getSimpleName());
		assertEquals(1, DatastoreServiceFactory.getDatastoreService().prepare(query)
			.countEntities());
	}

	@Test
	public void testNewMessage02() {
		IMessagesService service = injector.getInstance(IMessagesService.class);
		service.newMessage(UserServiceFactory.getUserService().getCurrentUser(), "abcde");
		service.newMessage(UserServiceFactory.getUserService().getCurrentUser(), "てすと");
		Query query = new Query(Messages.class.getSimpleName());
		assertEquals(2, DatastoreServiceFactory.getDatastoreService().prepare(query)
			.countEntities());
	}
}
