package control;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

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

import model.MD5;
import model.User;
import model.UserMod;

/**
 * Servlet implementation class Process
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 2L;

    /**
     * Default constructor. 
     */
    public Login() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String rep = request.getParameter("rep");				
		String name =  request.getParameter("user");
		String pass = request.getParameter("pass");
		try {
			pass = MD5.encode(pass);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("[Login] Không thể mã hóa MD5");
		}
		
		if (rep == null) {		// Normal Login
		name = name.replaceAll("[%']", "");
		User user = new User(name, pass, "", "", "","","");
		UserMod usermod = new UserMod();
		
		boolean isExist = usermod.checkLogin(user);
		
		if(isExist == true) {
			// Dat Session
			HttpSession session = request.getSession();
			session.setAttribute("user", name);
			// Ket Thuc Session
			response.sendRedirect("");
		}else {
			request.setAttribute("loginattempt", name);
			RequestDispatcher transfer = getServletContext().getRequestDispatcher("/index.jsp?customer=attempt");
			transfer.forward(request, response);
		}
	} 
		
		// Ajax Login
		else {
		name = name.replaceAll("[%']", "");
		User user = new User(name, pass, "", "", "","","");
		UserMod usermod = new UserMod();
		
		boolean isExist = usermod.checkLogin(user);
		
		if(isExist == true) {
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.getWriter().write("true");
			// Dat Session
			HttpSession session = request.getSession();
			session.setAttribute("user", name);
			
		}else {
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.getWriter().write("Tài khoản hoặc mật khẩu không đúng !");
		}
	}
	}
}
