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;

@WebService
@MTOM
public class Sklep {
	
	@WebResult(name="product")
	public List<Product> readAll() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.readAll();
		}
	}
	
//	@ResponseWrapper(localName = "wynikiWyszukiwania", targetNamespace = "http://soap.sklep/")
//	@WebResult(name="product", targetNamespace = "http://soap.sklep/model")

	@WebResult(name="product")
	public List<Product> readByPrice(@WebParam(name="min") BigDecimal min, @WebParam(name="max") BigDecimal max) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.findByPrice(min, max);
		}
	}
	
	@WebResult(name="product")
	public Product readOne(@WebParam(name="id") int productId) throws DBException, RecordNotFound {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.findById(productId);
		}
	}
	
	public void saveProduct(@WebParam(name="product") Product product) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			productDAO.save(product);
			db.commit();
		}
	}
	
    @WebResult(name="customer")
    public Customer oneCustomer(@WebParam(name="email") String email) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            CustomerDAO customerDAO = db.customerDAO();
            return customerDAO.findByEmail(email);
        }
    }
    
    @WebResult(name="order")
    public Order oneOrder(@WebParam(name="id") int orderId) throws DBException, RecordNotFound {
        try(DBConnection db = DBConnection.open()) {
            OrderDAO orderDAO = db.orderDAO();
            return orderDAO.findById(orderId);
        }
    }
    
	@WebResult(name="bytes")
	public byte[] getPhoto(@WebParam(name="id") int productId) throws DBException, RecordNotFound {
		return PhotoUtil.readBytes(productId);
	}

    public void savePhoto(@WebParam(name="id") int productId,
            @WebParam(name="bytes") byte[] bytes) {
        PhotoUtil.writeBytes(productId, bytes);
    }
}
