package sklep.web;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import sklep.db.DBConnection;
import sklep.db.DBException;
import sklep.db.ProductDAO;
import sklep.model.Product;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/products1")
public class Products1 extends HttpServlet {
       
    @Override
    protected void doGet(HttpServletRequest requets, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println("Zaraz odczytam produkty z bazy...");
        
        try(DBConnection c = DBConnection.open()) {
            ProductDAO productDAO = c.productDAO();
            List<Product> products = productDAO.readAll();
            for(Product p : products) {
                out.printf("Produkt nr %d to jest %s za cenę %s\n",
                        p.getProductId(), p.getProductName(), p.getPrice());
            }
        } catch (DBException e) {
            out.println("Bład: " + e);
            e.printStackTrace(out);
        }
    }
}
