package rest;

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

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import sklep.db.DBConnection;
import sklep.db.DBException;
import sklep.db.ProductDAO;
import sklep.db.RecordNotFound;
import sklep.model.Product;
import sklep.model.ProductList;
import sklep.photo.PhotoUtil;

// W tej wersji jednocześnie obsługiwane są różne formaty: xml, json, zwykły tekst, a docelowo PDF.
@Path("/products")
public class RProducts {

    @GET
    @Produces({"application/json", "application/xml", "text/plain"})
    public ProductList readAll() throws DBException {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            return new ProductList(productDAO.readAll());
        }
    }
    
    @GET
    @Path("/{id}")
    @Produces({"application/json", "application/xml", "text/plain"})
    public Product readOne(@PathParam("id") int productId) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            return productDAO.findById(productId);
        }
    }
    
    @GET
    @Path("/{id}/price")
    @Produces({"application/json", "text/plain"})
    public BigDecimal getPrice(@PathParam("id") int productId) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            return productDAO.findById(productId).getPrice();
        }
    }
    
    // W metodach obsługujących PUT i POST powinien występować jeden paramrtr bez żadnej adnotacji.
    // To właśnie w tym parametrze zostanie przekazana treść przysłana w zapytaniu ("body" / "content" / "entity")
    @PUT
    @Path("/{id}/price")
    @Consumes({"application/json", "text/plain"})
    public void setPrice(
                @PathParam("id") int productId,
                BigDecimal newPrice
            ) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            Product product = productDAO.findById(productId);
            product.setPrice(newPrice);
            productDAO.update(product);
            db.commit();
        }
    }
    
    @POST
    @Consumes({"application/json", "application/xml"})
    public Product add(Product product) throws DBException {
        try(DBConnection db = DBConnection.open()) {
            ProductDAO productDAO = db.productDAO();
            productDAO.save(product);
            db.commit();
            return product;
        }
    }
    
    @GET
    @Path("/{id}/photo")
    @Produces("image/jpeg")
    public byte[] photo(@PathParam("id") int productId) throws DBException, RecordNotFound {
        return PhotoUtil.readBytes(productId);
    }
}
