package com.demo.sklep.rest;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

import com.demo.sklep.model.Product;
import com.demo.sklep.photo.PhotoUtil;
import com.demo.sklep.repository.ProductRepository;

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;

@Path("/products")
@Produces("application/json")
@Consumes("application/json")
public class RProduct {
	@Autowired
	private ProductRepository productRepository;
	@Autowired
	private PhotoUtil photoUtil;

	@GET
	public List<Product> readAll() {
		return productRepository.findAll();
	}
	
	@Path("/{id}")
	@GET
	public Product readOne(@PathParam("id") int id) {
		return productRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
	}
	
	@Path("/{id}/price")
	@GET
	public BigDecimal getPrice(@PathParam("id") Integer id) {
		Optional<Product> product = productRepository.findById(id);
		if(product.isPresent()) {
			return product.get().getPrice();
		} else {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND);
		}
	}
	
	@Path("/{id}/price")
	@PUT
	public void setPrice(@PathParam("id") Integer id, BigDecimal newPrice) {
		Optional<Product> product = productRepository.findById(id);
		if(product.isPresent()) {
			Product realProduct = product.get();
			realProduct.setPrice(newPrice);
			productRepository.save(realProduct);
		} else {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND);
		}
	}
	
	@Path("/{id}")
	@PUT
	public void update(@PathParam("id") Integer productId, Product product) {
		// Aby mieć pewność, że zapisujemu produkt o typ ID, wpisuję productId z URL-a.
		// Ewentualnie możnaby jeszcze sprawdzić czy rekord istnieje, czy ID się zgadza
		// i jeśli coś jest nie tak, to wyrzucić wyjątek.
		product.setProductId(productId);
		productRepository.save(product);
	}

	@POST
	public Product insert(Product product) {
		product.setProductId(null);
		productRepository.save(product);
		
		return product;
	}

	@Path("/{id}")
	@DELETE
	public void delete(@PathParam("id") Integer productId) {
		try {
			productRepository.deleteById(productId);
		} catch (EmptyResultDataAccessException e) {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Brak produktu nr " + productId);
		}
	}
	
	@GET
	@Path("/{id}/photo")
	@Produces("image/jpeg")
	public byte[] getPhoto(@PathParam("id") int productId) {
		return photoUtil.readBytes(productId);
	}

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