package agilpizza.servlet;

import java.io.IOException;

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

import agilpizza.dao.CategoriaDAO;
import agilpizza.modelo.Categoria;
import agilpizza.modelo.Ingrediente;
import agilpizza.modelo.Pizza;

public class mudaPreco extends HttpServlet {
	private Pizza pizza; 

	private ServletContext servletContext;// = this.getServletContext();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		CategoriaDAO categoriaDAO = (CategoriaDAO)CategoriaDAO.getCategoriaDAO();

		//CategoriaDAO categoriaDAO=new CategoriaDAO();
		//Pizza 

		try{
			if(categoriaDAO==null){
				categoriaDAO=new CategoriaDAO();
			}
			for(Categoria categoria:categoriaDAO.buscaCategorias()){
				setPreco(categoria,req,resp);

			}
		}
		catch(Exception ex ){
			req.setAttribute("erro", "Preço invalido");
			RequestDispatcher disp = req.getRequestDispatcher("ingredientes.jsp");

			disp.forward(req, resp);
			//resp.getOutputStream().println(ex.getMessage()+" "+ex.getStackTrace());
			return;

		}

		//req.getSession().setAttribute("pizza", pizza);
		if(servletContext == null) 
			servletContext = this.getServletContext();
		
		servletContext.setAttribute("categoriasDao",categoriaDAO);
		resp.sendRedirect("ingredientes.jsp");
	}
	
	private void setPreco(Categoria categoria,HttpServletRequest req,HttpServletResponse resp) throws Exception{
		for(Ingrediente ingrediente: categoria.getIngredientes()){
			String valor=req.getParameter(ingrediente.getNome());
			if(valor!=null &&!valor.equals("") ){
				ingrediente.setPreco(Double.parseDouble(valor));
				//		resp.getOutputStream().println("ingrediente ="+ingrediente.getNome()+" "+valor);
				//	resp.flushBuffer();
			}
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		doGet(req,resp);
	}
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

}
