package sklep.serwlety;

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

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
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 javax.transaction.UserTransaction;

import sklep.model.Product;

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

	@PersistenceContext(unitName="sklep_pu")
	private EntityManager em;
	
	@Resource
	private UserTransaction transaction; // konwencja nazw: utx

	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"));
		}
		
		try {
			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 | RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException | NotSupportedException e) {
		} catch (Exception e) {
			throw new ServletException("wielka bieda", e);
		}
		
	}

}
