package sklep.rest;

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

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.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;

@Path("/products.xml")
public class RProductsXML {

	@GET
	@Produces("application/xml")
	public ProductList wszystkieProdukty() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return new ProductList(productDAO.readAll());
		}
	}
	
	@GET
	@Path("/{id}")
	@Produces("application/xml")
	public Product produktWgId(@PathParam("id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.findById(productId);
		}
	}
	
	// Pojedyncza wartość liczbowa lub tekstowa NIE JEST poprawnym (samodzielnym) XML-em
	// Dlatego tu wyjątkowo użjemy text/plain.
	@GET
	@Path("/{id}/price")
	@Produces("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();
		}
	}
	
	@PUT
	@Path("/{id}/price")
	@Consumes("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.save(product);
			db.commit();
		}
	}
	
	@POST
	@Consumes("application/xml")
	@Produces("application/xml")
	public Product zapiszProdukt(Product product) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			productDAO.save(product);
			db.commit();
			return product;
		}
	}
	
	@DELETE
	@Path("/{id}")
	public void usun(@PathParam("id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			productDAO.delete(productId);
			db.commit();
		}
	}
	
	@GET
	@Path("/{id}/photo")
	@Produces("image/jpeg")
	public byte[] foto(@PathParam("id") int productId) throws DBException, RecordNotFound {
		return PhotoUtil.readBytes(productId);
	}
	
}

