package sklep.rest;

import jakarta.ws.rs.*;
import sklep.db.DBConnection;
import sklep.db.DBException;
import sklep.db.ProductDAO;
import sklep.db.RecordNotFound;
import sklep.model.Price;
import sklep.model.Product;
import sklep.model.ProductList;

import java.math.BigDecimal;
import java.util.List;

@Path("/products.xml")
@Produces("application/xml")
@Consumes("application/xml")
public class RProductsXml {
    @GET
    public ProductList allProducts() throws DBException {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            return new ProductList(productDAO.readAll());
        }
    }

    @GET
    @Path("/{id}")
    // przykładowo /api/products.xml/3
    public Product oneProduct(@PathParam("id") int productId) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            return productDAO.findById(productId);
        }
    }

    @POST
    public void saveProduct(Product product) throws DBException {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            productDAO.save(product);
            db.commit();
        }
    }

    @GET
    @Path("/{id}/price")
    public Price getPrice(@PathParam("id") int productId) throws DBException, RecordNotFound {
        return new Price(oneProduct(productId).getPrice());
    }

    @PUT
    @Path("/{id}/price")
    public void setPrice(@PathParam("id") int productId, Price newPrice) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            Product product = productDAO.findById(productId);
            product.setPrice(newPrice.getValue());
            productDAO.save(product);
            db.commit();
        }
    }

    @GET
    @Path("/{id}/photo")
    @Produces("image/jpeg")
    public byte[] getPhoto(@PathParam("id") int productId) throws DBException, RecordNotFound {
        return PhotoUtil.readBytes(productId);
    }

    @PUT
    @Path("/{id}/photo")
    @Consumes("image/jpeg")
    public void getPhoto(@PathParam("id") int productId, byte[] bajty) {
        PhotoUtil.writeBytes(productId, bajty);
    }
}
