package kalkulator;

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

import org.apache.commons.lang3.StringUtils;

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

@WebServlet("/Kalkulator2")
public class Kalkulator2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html><head>");
		out.println("<title>Kalkulator serwletowy</title>");
		out.println("<link rel='stylesheet' type='text/css' href='styl.css'>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Kalkulator</h1>");
		out.println("<form>");
		out.println("<input type='number' name='liczba1'>");
		out.println("<select name='operacja'>");
		out.println("<option value='+'>+</option>");
		out.println("<option value='-'>-</option>");
		out.println("<option value='*'>*</option>");
		out.println("<option value='/'>/</option>");
		out.println("</select>");		
		out.println("<input type='number' name='liczba2'>");
		out.println("<button>Oblicz</button>");
		out.println("</form>");
		
		String param1 = request.getParameter("liczba1");
		String param2 = request.getParameter("liczba2");
		String operacja = request.getParameter("operacja");
		
		if(StringUtils.isNoneBlank(param1, param2, operacja)) {
			try {
				long liczba1 = Long.parseLong(param1);
				long liczba2 = Long.parseLong(param2);
				long wynik = switch(operacja) {
					case "+" -> liczba1 + liczba2;
					case "-" -> liczba1 - liczba2;
					case "*" -> liczba1 * liczba2;
					case "/" -> liczba1 / liczba2;
					default -> throw new IllegalArgumentException("Nieznane działanie: " + operacja);
				};
				out.printf("<div class='wynik'>%d %s %d = <strong>%d</strong></div>\n",
						liczba1, operacja, liczba2, wynik);
			} catch (NumberFormatException e) {
				out.printf("<div class='error'>Niepoprawny format liczby</div>\n");
			} catch(Exception e) {
				out.printf("<div class='error'>Błąd: %s</div>\n", e.getMessage());				
			}
		}
		out.println("</body>");
		out.println("</html>");
	}

}
