package com.atomikos.tomcat.web;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.atomikos.tomcat.demo.AccountManager;

@Controller
@RequestMapping("/jms")
public class JmsController {

	private javax.jms.ConnectionFactory connectionFactory;

	@Autowired
	@Qualifier("xaFactory")
	public void setConnectionFactory(
			javax.jms.ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	private javax.jms.Queue queue;

	@Autowired
	public void setQueue(javax.jms.Queue queue) {
		this.queue = queue;
	}

	private AccountManager accountManager;

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView withdrawWithJmsAndBalance(
			@RequestParam(required = false, defaultValue = "1") int account,
			@RequestParam(required = false, defaultValue = "50") int amount)
			throws InterruptedException, JMSException {

		Connection c = connectionFactory.createConnection();
		Session session = c.createSession(true, 0);
		MessageProducer sender = session.createProducer(queue);
		MapMessage m = session.createMapMessage();

		m.setIntProperty("account", account);
		m.setIntProperty("amount", amount);
		sender.send(m);
		session.close();
		c.close();

		// let's wait a little as JMS is asynchronous...
		Thread.sleep(500);
		return balanceAccount(account);
	}

	private ModelAndView balanceAccount(int account) {
		long amount = 0;

		try {
			amount = accountManager.balance(account);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return new ModelAndView("view", "account", new Account(account, amount));
	}

}
