package com.shin1ogawa.service;

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

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

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

public class BoardService extends AbstractService<Board> {
	public static Board create(User user, String title) {
		Board board = new Board();
		board.setUser(user);
		board.setTitle(title);
		board.setCreated(new Date(System.currentTimeMillis()));
		return board;
	}

	@Override
	public Board save(Board entity) {
		Board board = super.save(entity);
		try {
			InternetAddress address = new InternetAddress(
					"shin1ogawa@gmail.com", "Shinichi Ogawa", "iso-2022-jp");
			Session session = Session
					.getDefaultInstance(new Properties(), null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(address);
			message.addRecipient(Message.RecipientType.TO, address);
			message.setReplyTo(new InternetAddress[] { new InternetAddress(
					"noreply@shin1ogawa.com") });
			message.setSubject("新しいboardが追加されました。", "iso-2022-jp");
			StringBuilder b = new StringBuilder();
			b.append("タイトル=").append(board.getTitle()).append("\n");
			b.append("作成者=").append(
					board.getUser() != null ? board.getUser().getEmail()
							: "annonymous").append("\n");
			b.append("id=").append(board.getId()).append("\n");
			message.setText(b.toString(), "iso-2022-jp");
			Transport.send(message);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return board;
	}
}
