package agilpizza.servlet;

import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;

import java.io.IOException;

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

import org.junit.Before;
import org.junit.Test;

import agilpizza.Constantes;
import agilpizza.modelo.Pedido;
import agilpizza.modelo.PizzaMontada;

public class MontaIngredientesServletTest {

	private MontaIngredientesServlet servlet;

	private HttpServletRequest req;

	private HttpServletResponse resp;

	private HttpSession session;

	private RequestDispatcher dispatcher;

	private Object[] mocks;

	@Before
	public void setUp() throws Exception {
		servlet = new MontaIngredientesServlet();
		req = createNiceMock(HttpServletRequest.class);
		resp = createStrictMock(HttpServletResponse.class);
		session = createNiceMock(HttpSession.class);
		dispatcher = createNiceMock(RequestDispatcher.class);
		mocks = new Object[] { req, resp, session, dispatcher };
	}

	@Test
	public void testaIngredientesSelecionados() throws Exception {
		String[] ingredientes = new String[2];
		ingredientes[0] = "Provolone";
		ingredientes[0] = "Muzzarela";
		expect(req.getParameterValues("ingrediente")).andReturn(ingredientes);

		verificaSucesso();
	}

	@Test
	public void testaNenhumIngredienteSelecionado() throws Exception {
		String[] ingredientes = new String[0];
		expect(req.getParameterValues("ingrediente")).andReturn(ingredientes);

		verificaSucesso();
	}

	@Test
	public void testaListaDeIngredientesNula() throws Exception {
		expect(req.getParameterValues("ingrediente")).andReturn(null);

		verificaSucesso();
	}

	@Test
	public void testaIngredienteQueNaoExiste() throws Exception {
		String[] ingredientes = new String[1];
		ingredientes[0] = "Sapato";
		expect(req.getParameterValues("ingrediente")).andReturn(ingredientes);

		verificaSucesso();
	}

	private void verificaSucesso() throws IOException, ServletException {
		expect(req.getSession()).andReturn(session).times(2);
		expect(session.getAttribute(Constantes.PEDIDO)).andReturn(null);
		session.setAttribute(eq(Constantes.PEDIDO), isA(Pedido.class));
		req.setAttribute(eq("pizzaMontada"), isA(PizzaMontada.class));
		expect(req.getRequestDispatcher("mostraPizza.jsp")).andReturn(dispatcher);
		dispatcher.forward(eq(req), eq(resp));

		replay(mocks);
		servlet.doPost(req, resp);
		verify(mocks);
	}
}
