package sklep.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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.Price;
import sklep.model.Product;
import sklep.model.ProductList;
import sklep.photo.PhotoUtil;

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

	@GET
	public ProductList readAll() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return new ProductList(productDAO.readAll());
		}
	}
	
	@GET
	@Path("/{id}")
	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")
	public Price getPrice(@PathParam("id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			Product product = productDAO.findById(productId);
			return new Price(product.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.update(product);
			db.commit();
		}
	}
	
	@POST
	public Product addProduct(Product product) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			if(product.getProductId() != null) {
				throw new IllegalArgumentException("Nowy produkt nie może mieć ustawionego ID");
			}
			productDAO.insertNew(product);
			db.commit();
			return product;
		}
	}
	
	@DELETE
	@Path("/{id}")
	public void removeProduct(@PathParam("id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			if(productDAO.delete(productId)) {
				db.commit();
			} else {
				throw new RecordNotFound("Nie ma produktu nr " + productId);
			}
		}
	}
	
	@GET
	@Path("/{id}/photo")
	@Produces("image/jpeg")
	public byte[] getPhoto(@PathParam("id") int productId) throws DBException, RecordNotFound {
		return PhotoUtil.readBytes(productId);
	}

}
