package com.shin1ogawa.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.List;

import javax.jdo.Query;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.junit.Before;
import org.junit.Test;

import com.google.appengine.api.mail.MailServicePb.MailMessage;
import com.google.appengine.api.mail.dev.LocalMailService;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.development.ApiProxyLocalImpl;
import com.google.apphosting.api.ApiProxy;
import com.shin1ogawa.entity.Board;

public class BoardServiceTest extends AbstractServiceTest {
	LocalMailService mailService;

	@Before
	public void setUp() {
		super.setUp();
		ApiProxyLocalImpl proxy = (ApiProxyLocalImpl) ApiProxy.getDelegate();
		mailService = (LocalMailService) proxy.getService("mail");
		mailService.clearSentMessages();
	}

	@Test
	public void create01() {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		BoardService test = new BoardService();
		Board board = BoardService.create(user, "test title1");
		test.save(board);

		// assert the mail message.
		List<MailMessage> sentMessages = mailService.getSentMessages();
		assertEquals(sentMessages.size(), 1);
		MailMessage message = sentMessages.get(0);
		assertEquals(message.getSender(),
				"Shinichi Ogawa <shin1ogawa@gmail.com>");
		assertEquals(message.getSubject(), "新しいboardが追加されました。");
		assertEquals(message.getReplyTo(), "noreply@shin1ogawa.com");
		System.out.println(message.getTextBody());

		Query query = test.newQuery();
		query.setOrdering("created desc");
		List<Board> list = test.list(query);
		assertEquals(1, list.size());
		assertEquals("test title1", list.get(0).getTitle());
		Long id = list.get(0).getId();
		Board byIdString = test.getById(id);
		assertNotNull(byIdString);
	}

	@Test
	public void delete01() {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		BoardService test = new BoardService();
		Board board1 = BoardService.create(user, "test title1");
		test.save(board1);
		Board board2 = BoardService.create(user, "test title2");
		test.save(board2);
		Query query = test.newQuery();
		query.setOrdering("created desc");
		List<Board> list = test.list(query);
		assertEquals(2, list.size());
		for (Board board : list) {
			System.out.println(ToStringBuilder.reflectionToString(board));
		}
		assertEquals("test title1", list.get(1).getTitle());
		assertEquals("test title2", list.get(0).getTitle());
		test.delete(board1, board1.getKey());

		list = test.list(query);
		assertEquals(1, list.size());
		assertEquals("test title2", list.get(0).getTitle());
	}
}
