package sklep.serwlety;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sklep.model.Product;

@WebServlet("/zmiana2")
public class Zmiana2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@PersistenceUnit(unitName="sklep_pu")
	private EntityManagerFactory emf;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		if(request.getParameter("id") == null) {
			out.println("Trzeba podać id produktu");
			return;
		}
		
		Integer id = Integer.valueOf(request.getParameter("id"));
		BigDecimal podwyzka = null;
		if(request.getParameter("podwyzka") != null) {
			podwyzka = new BigDecimal(request.getParameter("podwyzka"));
		}
		
		EntityManager em = null;
		try {
			em = emf.createEntityManager();
			EntityTransaction transaction = em.getTransaction();
			transaction.begin();
			
			Product product = em.find(Product.class, id);
			if(product == null) {
				out.println("Nie znaleziono produktu o numerze " + id);
				return;
			}
			
			out.println(product.getProductName() + " " + product.getPrice());
			
			if(podwyzka != null) {
				product.setPrice(product.getPrice().add(podwyzka));
			}
			
			out.println("Po zmianie:");
			out.println(product.getProductName() + " " + product.getPrice());
			
			transaction.commit();
			
		} catch (SecurityException | IllegalStateException e) {
			throw new ServletException("wielka bieda", e);
		} finally {
			if(em != null) {
				em.close();
			}
		}
		
	}

}
