package sklep.soap;

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

import jakarta.jws.WebParam;
import jakarta.jws.WebResult;
import jakarta.jws.WebService;
import jakarta.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> wszystkieProdukty() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.readAll();
		}
	}
	
	@WebResult(name="product")
	public Product produktWgId(@WebParam(name="id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.findById(productId);
		}
	}
	
	@WebResult(name="product")
	public List<Product> produktyWgCen(
			@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);
		}
	}
	
	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="order")
	public Order zamowienieWgId(@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 Customer klient(@WebParam(name="email") String email) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			return customerDAO.findByEmail(email);
		}
	}
	
	@WebResult(name="bytes")
	public byte[] foto(@WebParam(name="id") int productId) throws DBException, RecordNotFound {
		return PhotoUtil.readBytes(productId);
	}
	
}
