package mainapp;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterAction extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NoSuchAlgorithmException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        
        String name = request.getParameter("name");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String afm = request.getParameter("afm");
        String email = request.getParameter("email");
        String bank_no = request.getParameter("bank_no");
        
        if (!isNotNullOrEmpty(name) || !isNotNullOrEmpty(username) || !isNotNullOrEmpty(password) || !isNotNullOrEmpty(afm) ||
                !isNotNullOrEmpty(phone) || !isNotNullOrEmpty(address) || !isNotNullOrEmpty(email) ||
                !isNotNullOrEmpty(bank_no)) {
            request.setAttribute("errorMessage", "Παρακαλώ συμπληρώστε όλα τα πεδία");
            request.setAttribute("name", name);
            request.setAttribute("username", username);
            request.setAttribute("password", password);
            request.setAttribute("afm", afm);
            request.setAttribute("phone", phone);
            request.setAttribute("address", address);
            request.setAttribute("email", email);
            request.setAttribute("bank_no", bank_no);
            request.getRequestDispatcher("?action=register").forward(request, response);
            return;
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            request.setAttribute("errorMessage", "Συνέβει κάποιο σφάλμα. Παρακαλώ προσπαθήστε ξανά #1");
            request.getRequestDispatcher("?action=register").forward(request, response);
            return;
        }
        md.update(password.getBytes());
        //byte[] passBytes = password.getBytes("UTF-8");
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
             sb.append(String.format("%02x", b & 0xff));
        }
        String md5pass = sb.toString();
        Map<String, String> fields = new HashMap<String, String>();
        fields.put("name", name);
        fields.put("username", username);
        fields.put("password", md5pass);
        fields.put("afm", afm);
        fields.put("phone", phone);
        fields.put("address", address);
        fields.put("email", email);
        fields.put("bank_account", bank_no);
        try {
            DB.insertRow("user", fields);
        } catch (ClassNotFoundException ex) {
            request.setAttribute("errorMessage", "Συνέβει κάποιο σφάλμα. Παρακαλώ προσπαθήστε ξανά #2");
            request.getRequestDispatcher("?action=register").forward(request, response);
            return;
        } catch (SQLException ex) {
            // mysql error code 1062 means a UNIQUE KEY constraint failed. Username is unique.
            if (ex.getErrorCode() == 1062) {
                request.setAttribute("errorMessage", "Παρακαλώ συμπληρώστε όλα τα πεδία");
                request.setAttribute("name", name);
                request.setAttribute("username", username);
                request.setAttribute("password", password);
                request.setAttribute("afm", afm);
                request.setAttribute("phone", phone);
                request.setAttribute("address", address);
                request.setAttribute("email", email);
                request.setAttribute("bank_no", bank_no);
                request.setAttribute("errorMessage", "Το όνομα χρήστη υπάρχει ήδη. Παρακαλώ διαλέξτε κάποιο άλλο.");
                request.getRequestDispatcher("?action=register").forward(request, response);
            }
            else {
                request.setAttribute("errorMessage", "Συνέβει κάποιο σφάλμα. Παρακαλώ προσπαθήστε ξανά #3");
                request.getRequestDispatcher("?action=register").forward(request, response);
            }
            return;
        }
        response.sendRedirect("?action=login&reg=1");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(RegisterAction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(RegisterAction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    protected boolean isNotNullOrEmpty (String str) {
        if (str == null || str.length() < 1) {
            return false;
        }
        return true;
    }
}
