package com.mockobjects.examples.calcserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CalculatorServlet extends HttpServlet {
    IntCalculator myCalculator;


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        performTask(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        performTask(request, response);
    }

    public String getServletInfo() {
        return super.getServletInfo();
    }

    public void init() throws ServletException {
        try {
            Connection connection = Database.createConnection();
            myCalculator =
                    new SqlSavingCalculator(
                            new Calculator(),
                            connection.prepareStatement("INSERT INTO LOG VALUES (?)"));
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }


    public void init(IntCalculator calculator) {
        myCalculator = calculator;
    }


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

        PrintWriter wr = response.getWriter();
        try {
            int value1 = Integer.parseInt(request.getParameter("value1"));
            int value2 = Integer.parseInt(request.getParameter("value2"));

            String operation = request.getPathInfo();
            wr.println(myCalculator.calculate(value1, value2, operation));
        } catch (NumberFormatException ex) {
            wr.println("Calculation failed " + ex);
        } catch (CalculatorException ex) {
            wr.println("Calculation failed " + ex);
        }
    }
}