package com.shin1ogawa.service;

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

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.appengine.api.users.User;
import com.google.inject.Inject;
import com.shin1ogawa.entity.Messages;

public class MessagesService implements IMessagesService {

	static final Logger LOGGER = LoggerFactory.getLogger(MessagesService.class);

	@Inject
	PersistenceManager em;


	public Messages newMessage(User user, String messageBody) {
		Messages message = new Messages();
		message.setUserName(user != null ? user.getNickname() : "unknown");
		message.setMessage(messageBody);
		message.setUpdated(new Date(System.currentTimeMillis()));

		Transaction transaction = em.currentTransaction();
		try {
			transaction.begin();
			em.makePersistent(message);
			transaction.commit();
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		return message;
	}

	public List<Messages> listAll() {
		Query query = em.newQuery(Messages.class);
		query.setOrdering("updated desc");
		@SuppressWarnings("unchecked")
		List<Messages> resultList = (List<Messages>) query.execute();
		return resultList;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
