package sklep.rest;

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

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import sklep.model.Product;
import sklep.repository.ProductRepository;

@RestController
@RequestMapping("/products.json")
public class ProductEndpointJson {
	private ProductRepository productRepository;
	
	public ProductEndpointJson(ProductRepository productRepository) {
		this.productRepository = productRepository;
	}

	@GetMapping
	public List<Product> getAllProducts() {
		return productRepository.findAll();
	}
	
	@GetMapping("/{id}")
	public Product getOneProduct(@PathVariable("id") Integer id) {
		return productRepository
				.findById(id)
				.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
	}

	  
    @GetMapping(path="/{id}/price", produces="text/plain")
    public BigDecimal getPrice(@PathVariable Integer id) {
        return getOneProduct(id).getPrice();
    }
    
    @PutMapping("/{id}/price")
    public void setPrice(@PathVariable Integer id, @RequestBody BigDecimal newPrice) {
        Product product = productRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
        product.setPrice(newPrice);
        productRepository.save(product);
    }
    
    @PostMapping
    public Product insert(@RequestBody Product product) {
    /* Operacja save (a wewnętrznie persist z Hibernate) spowoduje ustawienie nowego ID w obiekcie.
     * Warto taką informację przekazać klientowi. Można:
     * 1) odesłać uzupełniony rekord (i tak zrobimy tutaj),
     * 2) odesłać "małego JSON-a" z informacją o tym ID
     *    (i innymi informacjami, które serwer chce przekazać klientowi)
     * 3) tylko nagłówek Location z URL-em nowego rekordu (to zobaczymy w wersji JAX-RS).
     */
        productRepository.save(product);
        return product;
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") Integer productId) {
        try {
            productRepository.deleteById(productId);
        } catch (EmptyResultDataAccessException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Brak produktu nr " + productId);
        }
    }
    
}
