package agilpizza.servlet;

import java.io.IOException;

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

import agilpizza.dao.ClienteDAO;
import agilpizza.modelo.Cliente;

public class IdentificarCliente extends HttpServlet {

	ClienteDAO clienteDao;
	
	@Override
	public void init() throws ServletException {
		super.init();
		clienteDao = (ClienteDAO)this.getServletContext().getAttribute("clienteDAO");
		if (clienteDao == null) {
			clienteDao = new ClienteDAO();
			this.getServletContext().setAttribute("clienteDAO", clienteDao);
		}
	}

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, IOException {
		String email = (String) req.getParameter("email");

		if (!ValidacaoUtil.isValidEmail(email)) {
			//ERRO
			String msgErro = "É necessário preencher um email válido para identificação.";
			req.getSession().setAttribute("msgErro", msgErro);	
			resp.sendRedirect("identificacaoCliente.jsp");
			req.getSession().setAttribute("clienteIdentificado", null);
			return;
		}
		
		//OK
		req.getSession().setAttribute("msgErro", null);	
		Cliente cliente = this.clienteDao.procuraCliente(email);
		if (cliente == null) {
			cliente = new Cliente(email);
			this.clienteDao.gravaCliente(cliente);
		}
		
		req.getSession().setAttribute("clienteIdentificado", cliente);
		
		resp.sendRedirect("cliente.jsp");
	}

	
	
	
	@Override
	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(arg0, arg1);
	}


	public void setClienteDao(ClienteDAO clienteDAO) {
		this.clienteDao = clienteDAO;
		
	}
	
}
