package com.servlets;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.artifacts.FactoryProvider;
import com.entities.User;


public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public RegisterServlet() {
        super();
        
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html;charset=UTF-8");
    	try(PrintWriter out = response.getWriter()){
    		try {
    			String userName = request.getParameter("user_name");
    			String userEmail = request.getParameter("user_email");
    			String userPhone = request.getParameter("user_phone");
    			String userPassword = request.getParameter("user_password");
    			
    			User user = new User(userName, userEmail, userPhone, userPassword);
    			Session hibernateSession = FactoryProvider.getFactory().openSession();
    			Transaction tx = hibernateSession.beginTransaction();
    			int userId = (int) hibernateSession.save(user);
    			System.out.println(userId);
    			
    			
    			tx.commit();
    			
    			hibernateSession.close();
    			
    			response.sendRedirect("message.jsp");
    			
    			
    		}catch(Exception e) {
    			
    		}
    		
    		
    		
    	}
    	
    	
    	
    	
    	
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

}
