package digitalgraffiti.web;

import digitalgraffiti.models.MessagePost;

import digitalgraffiti.models.Post;
import org.json.JSONObject;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.JMSProducer;
import javax.jms.Queue;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/post")
public class PostServlet extends HttpServlet
{
	@EJB
	private WebRepository repository;

	@Resource(mappedName = "java:/PostQueue")
	private Queue queue;

	@Inject
	private JMSContext jmsContext;

	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException, IOException
	{
		String id = request.getParameter("id");

		Post post = this.repository.getPost(id);

		response.getWriter().print(post.toJSON());
	}

	protected void doPost(
		HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException, IOException
	{
		JSONObject json = (JSONObject)request.getAttribute("json");
		String sessionId = request.getSession().getId();
		MessagePost post = new MessagePost(json, sessionId);

		this.repository.savePost(post);

		JSONObject id = new JSONObject();
		id.put("id", post.getId());

		response.getWriter().print(id);

		JMSProducer jmsProducer = this.jmsContext.createProducer();
		jmsProducer.send(this.queue, post.toJSON().toString());
	}
}
