package serwlety.podstawy;

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

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/kalkulator")
public class Kalkulator extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String poczatek = """
                <!DOCTYPE html>
                <html>
                <head>
                <title>Rozmowa serlwetowa</title>
                </head>
                <body>""";
        final String formularz = """
                <form>
                <label for="liczba1">Pierwsza liczba:</label>
                <input name="liczba1">
                <br/>
                <label for="liczba2">Druga liczba:</label>
                <input name="liczba2">
                <br/>
                <button>Wyślij</button>
                </form>""";
        final String koniec = """
                </body>
                </html>""";
        response.setContentType("text/html"); // MIME type / Content-Type
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println(poczatek);
        out.println(formularz);

        try {
            int liczba1 = Integer.parseInt(request.getParameter("liczba1"));
            int liczba2 = Integer.parseInt(request.getParameter("liczba2"));
            out.println("<div>Suma " + (liczba1 + liczba2) + "</div>");
        } catch (NumberFormatException e) {
            out.println("Niepoprawny format liczby");
        }

        out.println(koniec);
    }
}
