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.UserMod;

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

    /**
     * Default constructor. 
     */
    public ChangePass() {
    	
    }

	/**
	 * @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 {
	    request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html; charset=UTF-8");	
		
	    HttpSession session = request.getSession();
		String user = (String) session.getAttribute("user");
		String passold = request.getParameter("passold");
		passold = passold.replaceAll("[%']", "");
		String passnew = request.getParameter("passnew");
		passnew = passnew.replaceAll("[%']", "");
		try {
			passold = MD5.encode(passold);
			passnew = MD5.encode(passnew);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
if (passold!=null ){
		UserMod usermod = new UserMod();
		boolean isCorrect = usermod.checkpass(user, passold);
		if(isCorrect == true) {
			
			usermod.changepass(user, passnew);
			request.setAttribute("passnew", passnew);
			RequestDispatcher transfer = getServletContext().getRequestDispatcher("/index.jsp?customer=changepw");
			transfer.forward(request, response);
			
		}else {
			// response.sendRedirect("success.jsp");
			request.setAttribute("passnewattempt", passnew);
			RequestDispatcher transfer = getServletContext().getRequestDispatcher("/index.jsp?customer=changepw");
			transfer.forward(request, response);
		}
		
	} else {
		response.sendRedirect("index.jsp");
	}
	}
}
