package sklep.soap;

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

import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.soap.MTOM;

import sklep.db.CustomerDAO;
import sklep.db.DBConnection;
import sklep.db.DBException;
import sklep.db.OrderDAO;
import sklep.db.ProductDAO;
import sklep.db.RecordNotFound;
import sklep.model.Customer;
import sklep.model.Order;
import sklep.model.Product;
import sklep.photo.PhotoUtil;

@WebService
@MTOM
public class Sklep {
	@WebResult(name="product")
	public List<Product> odczytajWszystkieProdukty() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.readAll();
		}
	}
	
	@WebResult(name="product")
	public List<Product> produktyWgCeny(
			@WebParam(name="min") BigDecimal minPrice,
			@WebParam(name="max") BigDecimal maxPrice
		) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.findByPrice(minPrice, maxPrice);
		}
	}
	
	@WebResult(name="product")
	public Product odczytajJedenProdukt(@WebParam(name="id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.findById(productId);
		}
	}
	
	@WebResult(name="order")
	public List<Order> odczytajWszystkieZamowienia() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			OrderDAO orderDAO = db.orderDAO();
			return orderDAO.readAll();
		}
	}
	
	@WebResult(name="order")
	public Order odczytajJednoZamowienie(@WebParam(name="id") int orderId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			OrderDAO orderDAO = db.orderDAO();
			return orderDAO.findById(orderId);
		}
	}
	
	@WebResult(name="customer")
	public List<Customer> odczytajWszystkichKlientow() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			return customerDAO.readAll();
		}
	}
	
	@WebResult(name="customer")
	public Customer odczytajJednegoKlienta(@WebParam(name="email") String email) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			return customerDAO.findByEmail(email);
		}
	}
	
	public void zapiszProdukt(@WebParam(name="product") Product product) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			productDAO.save(product);
			db.commit();
		}
	}
	
	@WebResult(name="bytes")
	public byte[] foto(@WebParam(name="id") int productId) throws DBException, RecordNotFound {
		return PhotoUtil.readBytes(productId);
	}
	// Dane binarne są domyślnie wstawiane do XML skonwertowane na format base64.
	// Po użyciu adnotacji @MTOM są dołączane jako załacznik do komunikatu SOAP
	// (to się nazywa "SOAP with Attachments").
}
