/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import hibernate.Userdata;
import hibernate.util.HibernateUtil;
import database.operations.CreatePlayerTable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import util.ConvertPassword;

/**
 *
 * @author Ani
 */
@WebServlet(name="Registration", urlPatterns={"/Registration"})
public class Registration extends HttpServlet {
    private Session hibernateSession;
    private PrintWriter out;
    /** 
     * 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 {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();       

        try {                              
            hibernateSession = HibernateUtil.getSessionFactory().openSession();
            hibernateSession.beginTransaction();

            String password = request.getParameter("password");
            String passwordAgain = request.getParameter("passwordAgain");
            String email = request.getParameter("email");
            String username = request.getParameter("username");

            if (!checkDataOfNewUser(password, passwordAgain, email,
                    username, request)){
                response.sendRedirect("registration.jsp");
            }
            else{
                insertNewUser(username, password, email);
                request.getSession().setAttribute("registered", true);
                response.sendRedirect("index.jsp");
            }
        } catch (Exception ex) {

        } finally {
            hibernateSession.getTransaction().commit();
            hibernateSession.close();
            out.close();
        }
    }

    private boolean checkDataOfNewUser(String password, String passwordAgain,
            String email, String username, HttpServletRequest request){
        if (username==null){
            request.getSession().setAttribute("message", "Nem adtál meg felhasználó nevet!");
            return false;
        }

        if (email==null){
            request.getSession().setAttribute("message", "Nem adtál meg e-mail címet!");
            return false;
        }

        if (username.length()<5){
            request.getSession().setAttribute("message", "Túl rövid felhasználó név!");
            return false;
        }

        if (!password.equals(passwordAgain)){
            request.getSession().setAttribute("message", "A jelszavak nem egyeznek");
            return false;
        }
        else if(password.length()<6){
            request.getSession().setAttribute("message", "Túl rövid jelszó!");
            return false;
        }
        
        if (!checkEmail(email)){
            request.getSession().setAttribute("message", "Nem e-mail cím!");
            return false;
        }

        Userdata ud = (Userdata) hibernateSession.get(Userdata.class, username);

        if (ud!=null){
            request.getSession().setAttribute("message", "A felhasználónév már foglalt!");
            return false;
        }

        Query query = hibernateSession.createQuery("FROM Userdata ud WHERE ud.email=:email");
        query.setString("email", email);

        if (query.list().size()!=0){
            request.getSession().setAttribute("message", "Az e-mail cím már foglalt!");
            return false;
        }

        return true;
    }


    private boolean checkEmail(String email){
        Pattern p = Pattern.compile("^[a-zA-Z0-9]+(\\.[_a-zA-Z0-9]+)*@" +
                "[a-zA-Z0-9]+(\\.[a-zA-Z0-9_]+)*\\.([a-z0-9A-Z]+)$");
        Matcher m = p.matcher(email);

        if (!m.matches()){
            return false;
        }
        return true;
    }

    private void insertNewUser(String username, String password, String email) throws SQLException, NoSuchAlgorithmException, UnsupportedEncodingException, IOException{
        Query query = hibernateSession.createQuery("SELECT max(us.id) FROM Userdata us");
        Integer id = (Integer) query.uniqueResult();

        Userdata newuser = new Userdata(username, ConvertPassword.convertPassword(password), email, id==null ? 1 : id+1,
                new java.sql.Date(System.currentTimeMillis()), "user_game_" + (id==null ? "" + 1 : "" + (id+1)));
        
        CreatePlayerTable.createPlayerTable(newuser.getTablename());
        hibernateSession.save(newuser);
        hibernateSession.save(newuser.getPassword());
        hibernateSession.save(newuser.getUserstatistic());
        
        }

    // <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 {
        processRequest(request, response);
    } 

    /** 
     * 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 {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
