package admin.control;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

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 AUser
 */
public class AUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AUser() {
        super();
        // 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 {
		response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8"); 
	    String rep = request.getParameter("rep");
		
	    if (rep.equals("view")){
	    	
	    	try {

	        	int records = new UserMod().recordsnumberUser();
	        	int pagenum = records / 9;
	        	if((records % 9) != 0) {
	        		pagenum++;
	        	}
	        	String Trang= (String)request.getParameter("page");
	        	if (Trang==null){Trang="1";}
	        	int pages = Integer.parseInt(Trang);
	        	if (pages < 1 || pages > pagenum){
	        		pages = 1;
	        	}

	        	// Phan Trang
	        	int offset = records - 9*pages ;
	        	int limit = 9;
	        	if (offset < 0 ){
	        		offset = 0;
	        		limit = records - 9*(pages-1);
	        	}
	        	// // Ket Thuc Phan Trang
	        	List<User> user = new UserMod().getAll(limit,offset);
	        	
	            request.setAttribute("alluser", user);
	            request.setAttribute("TongSoTrang", pagenum);


	            RequestDispatcher rd = request.getRequestDispatcher("admin/index.jsp?main=user&page="+Trang);
	            rd.forward(request, response);
	         }
	           
	           catch (SQLException ex) {
	            Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
	        } 
	    	    	
	    }
	    
	    if (rep.equals("delacustomer")){
	    	String username = request.getParameter("usern");
	    	String Trang= (String)request.getParameter("page");
	    	new UserMod().DeleteaCustomer(username);
	    	response.sendRedirect("AUser?rep=view&page="+Trang);
	    	
	    }
	    
		if (rep.equalsIgnoreCase("delchoise")){
			String idchoiced;
			String Trang = (String)request.getParameter("page");
			for (int i =1; i < 11; i++){
				idchoiced = (String)request.getParameter("idchoiced"+i);
				if (idchoiced != null){
					new UserMod().DeleteaCustomer(idchoiced);
				}
			}
			response.sendRedirect("AUser?rep=view&page="+Trang);
		}
	    
	    if (rep.equals("delall")){
	    	new UserMod().DeleteAllCustomer();
	    	response.sendRedirect("AUser?rep=view");
	    	
	    }
	    if (rep.equals("login")){
			String name =  request.getParameter("user");
			String pass = request.getParameter("pass");
			try {
				pass = MD5.encode(pass);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			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("admin/index.jsp");
			}else {
				response.sendRedirect("admin/login.jsp");
			}
	    }
	    
	    if (rep.equals("logout")){
	    	HttpSession session = request.getSession();
	    	session.removeAttribute("user") ; 
	    	response.sendRedirect("admin/index.jsp");
	    }
	    
	    if (rep.equals("logout-store")){
	    	HttpSession session = request.getSession();
	    	session.removeAttribute("user") ; 
        	session.removeAttribute("obj");
            session.removeAttribute("giohang"); 
	    	response.sendRedirect("index.jsp");
	    }
	    
	    if( rep.equals("changepw")){
	    	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("/admin/index.jsp?main=changepw");
				transfer.forward(request, response);
				
			}else {
				// response.sendRedirect("success.jsp");
				request.setAttribute("passnewattempt", passnew);
				RequestDispatcher transfer = getServletContext().getRequestDispatcher("/admin/index.jsp?main=changepw");
				transfer.forward(request, response);
			}
			
		} else {
			response.sendRedirect("index.jsp");
		}
	    	
	    }
	    
	    
	    
	}

}
