package agilpizza.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
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 agilpizza.modelo.Endereco;
import agilpizza.dao.ClienteDAO;
import agilpizza.modelo.Cliente;

public class EnderecoServlet extends HttpServlet {

	private static final long serialVersionUID = -4127253820264183478L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String cpf = (String) req.getParameter("cpf");
		String nome = (String) req.getParameter("nome");
		String rua = (String) req.getParameter("rua");
		String numero = (String) req.getParameter("numero");
		String complemento = (String) req.getParameter("complemento");
		String bairro = (String) req.getParameter("bairro");
		String cep = (String) req.getParameter("cep");
		String telefone = (String) req.getSession().getAttribute("telefone");
		String email = (String) req.getSession().getAttribute("email");
		
		if (ValidacaoUtil.isVazio(rua) || ValidacaoUtil.isVazio(numero)
				|| ValidacaoUtil.isVazio(bairro) || ValidacaoUtil.isVazio(nome)
				|| ValidacaoUtil.isVazio(cpf)) {
			req.getSession().setAttribute("mensagem", "Nome, CPF, rua, número e bairro são obrigatórios.");
			resp.sendRedirect("erro.jsp");
			return;
		}

		Endereco end = new Endereco(rua, numero, complemento, bairro, cep);
		Cliente cliente = new Cliente(nome, telefone, email, end, cpf);
		ServletContext context = this.getServletContext();
		ClienteDAO clienteDao = (ClienteDAO) context.getAttribute("clienteDao");
		clienteDao.adicionaCliente(cliente);

		HttpSession session = req.getSession();
		session.setAttribute("cliente", cliente);
		
		if(req.getParameter("listaNegra") != null){
			cliente.setInadimplente(true);
			resp.sendRedirect("listaNegra.jsp");
		}
		else{
			resp.sendRedirect("mostraEndereco.jsp");
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
