package com.shin1ogawa.service;

import static org.junit.Assert.assertEquals;

import java.util.Date;
import java.util.List;

import javax.jdo.Query;

import org.junit.Test;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.shin1ogawa.entity.Board;
import com.shin1ogawa.entity.Message;

public class MessageServiceTest extends AbstractServiceTest {

	BoardService boardService = new BoardService();

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

		MessageService test = new MessageService();
		final String body = "this is a test message.";
		Message message = MessageService.create(board, user, body);
		boardService.save(board);

		Query query = test.newQuery();
		List<Message> list = test.list(query);
		assertEquals(1, list.size());
		message = list.get(0);
		assertEquals(body, message.getBody());
	}

	@Test
	public void edit01() {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		Board board = BoardService.create(user, "test title1");
		boardService.save(board);
		Message message1 = new Message();
		message1.setUser(user);
		final String BODY1 = "this is first message.";
		message1.setBody(BODY1);
		message1.setCreated(new Date(System.currentTimeMillis()));
		board.getMessages().add(message1);
		Message message2 = new Message();
		message2.setUser(user);
		final String BODY2 = "これはtest title1板の2個目の投稿。";
		message2.setBody(BODY2);
		message2.setCreated(new Date(System.currentTimeMillis()));
		board.getMessages().add(message2);

		Query query = boardService.newQuery();
		query.setOrdering("created desc");
		List<Board> list = boardService.list(query);
		assertEquals(1, list.size());
		board = list.get(0);
		assertEquals("test title1", board.getTitle());
		assertEquals(2, board.getMessages().size());
		// Board#messagesは作成日時の降順になるよう設定している。
		assertEquals(BODY1, board.getMessages().get(1).getBody());
		assertEquals(BODY2, board.getMessages().get(0).getBody());

		// board.getMessages().remove(0);
		// Exception: java.lang.UnsupportedOperationException:
		//   Could not extract parent key from query expression.
		MessageService test = new MessageService();
		// messages(0)なのでBODY2が削除されるはず。
		test.delete(board.getMessages().get(0), board.getMessages().get(0).getKey());
		
		boardService.save(board);
		list = boardService.list(query);
		assertEquals(1, list.size());
		board = list.get(0);
		assertEquals("test title1", board.getTitle());
		assertEquals(1, board.getMessages().size());
		assertEquals(BODY1, board.getMessages().get(0).getBody());
	}
}
