package com.atomikos.examples.tomcat.jdbc;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class DemoServlet extends HttpServlet {
	DbPopulator dbPopulator;

	@Override
	public void init() throws ServletException {
		super.init();
		try {
			dbPopulator = new DbPopulator();
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/plain");

		try {
			Operation operation = getOperation(request);
			int account = getAccount(request);
			int amount = getAmount(request);
			
			if (operation == Operation.WITHDRAW) {
				dbPopulator.withdraw(account, amount);
			}

			String message  = "balance is " + dbPopulator.getBalance(account)
					+ " for account " + account;

			response.getWriter().write(message);
		} catch (Exception e) {
			e.printStackTrace(response.getWriter());
		}

	}

	private int getAmount(HttpServletRequest request) {
		String amount = request.getParameter("amount");
		if (amount == null)
			return 50;
		try {
			return Integer.parseInt(amount);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("amount must be an integer");
		}
	}

	private int getAccount(HttpServletRequest request) {
		String account = request.getParameter("account");
		if (account == null)
			return 1;
		try {
			return Integer.parseInt(account);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("account must be an integer");
		}
	}

	private Operation getOperation(HttpServletRequest request) {
		String operation = request.getParameter("operation");
		if (operation == null) {
			return Operation.BALANCE;
		}
		try {
			return Operation.valueOf(operation.toUpperCase());
		} catch (Exception e) {
			throw new IllegalArgumentException(
					"operation must be one of balance or withdraw");
		}
	}

}
