	package com.atomikos.tomcat.web;

import org.springframework.beans.factory.annotation.Autowired;
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("/jdbc")
public class JdbcController {

	private AccountManager accountManager;

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

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView balance(
			@RequestParam(required = false, defaultValue = "1") int account) {
		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));
	}

	@RequestMapping(value = "/withdraw", method = RequestMethod.GET)
	public ModelAndView withdraw(
			@RequestParam(required = false, defaultValue = "1") int account,
			@RequestParam(required = false, defaultValue = "50") int amount) {
		try {
			accountManager.withdraw(account, amount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return balanceAccount(account);
	}

}
