package com.shin1ogawa.logic;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.junit.Before;
import org.junit.Test;

import com.google.appengine.api.mail.MailServicePb.MailMessage;
import com.google.appengine.api.mail.dev.LocalMailService;

public class MailLogicTest extends AbstractLogicTest {
	LocalMailService mailService;

	@Before
	public void setUp() {
		super.setUp();
		mailService = (LocalMailService) getApiProxyLocal().getService("mail");
		mailService.clearSentMessages();
	}

	@Test
	public void メール送信機能のテスト機能のテスト() throws UnsupportedEncodingException,
			MessagingException {
		final String SENDER_ADDRESS = "shin1ogawa@gmail.com";
		final String SENDER_NAME = "Shinichi Ogawa";
		final String RECIPIENT_ADDRESS = "shin1o@yahoo.co.jp";
		final String SUBJECT = "サブジェクトです。";
		final String REPLY_TO_ADDRESS = "noreply@shin1ogawa.com";
		final String TEXT_BODY = "本文です。本文です。";

		InternetAddress address = new InternetAddress(SENDER_ADDRESS,
				SENDER_NAME, "iso-2022-jp");
		Session session = Session.getDefaultInstance(new Properties(), null);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(address);
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(
				RECIPIENT_ADDRESS));
		message.setReplyTo(new InternetAddress[] { new InternetAddress(
				REPLY_TO_ADDRESS) });
		message.setSubject(SUBJECT, "iso-2022-jp");
		message.setText(TEXT_BODY, "iso-2022-jp");
		MailLogic.send(message);
		// 
		List<MailMessage> sentMessages = mailService.getSentMessages();
		assertThat(sentMessages.size(), is(1));
		MailMessage sentMessage = sentMessages.get(0);
		assertThat(sentMessage.getSender(), is(SENDER_NAME + " <"
				+ SENDER_ADDRESS + ">"));
		assertThat(sentMessage.getSubject(), is(SUBJECT));
		assertThat(sentMessage.getReplyTo(), is(REPLY_TO_ADDRESS));
		assertThat(sentMessage.getTextBody(), is(TEXT_BODY));
	}
}
