package ru.mai.dep806;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
/**
 * Created by K_A_Volchica on 13.07.2015.
 */
public class TableServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int a = request.getParameter("a");
        int b = request.getParameter("b");
        try {
            String reply;
            if (a != Integer.parseInt(req.getParameter("a"))) {
                reply = "<div style='font-weight:bold;'>First number must be integer</div>";
            }
            if (b != Integer.parseInt(req.getParameter("b"))) {
                reply = "<div style='font-weight:bold;'>Second number must be integer</div>";
            } else if (a <= 0 | a >= 50 | b <= 0 | b >= 50) {
                reply = "<div style='font-weight:bold;'>Variables must be positive, but less than 50</div>";
            }
            catch(Exception ax)
            {
                reply = "<div style='color:red;font-weight:bold;'>Error: invalid numer</div>";
            }


            int[][] matrixA;
            matrixA = new int[a + 1][b + 1];
            for (int l = 0; l <= a; l++) {
                for (int m = 0; m <= b; m++) {
                    matrixA[l][m] = l * m;
                }
            }
            out.println("<html>");
            out.println("<head>");
            out.println("<title>TableServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(reply);
            out.println("<TABLE>");
            for (int j = 1; j <= b; j++) {
                out.println("<TR>");
                for (int i = 1; i <= a; i++) {
                    out.println("<TH>" + matrixA[i][j] + "=" + i + "*" + j + "</TH>");
                }
                out.println("</TR>");
            }

            out.println("</TABLE>");
            out.println("</body>");
            out.println("</html>");

        }finally {
                out.close();
            }
    }
}
