package sklep.soap;

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

import jakarta.jws.WebService;
import jakarta.xml.ws.soap.MTOM;
import sklep.db.CustomerDAO;
import sklep.db.DBConnection;
import sklep.db.OrderDAO;
import sklep.db.ProductDAO;
import sklep.exn.DBException;
import sklep.exn.RecordNotFound;
import sklep.model.Customer;
import sklep.model.Order;
import sklep.model.Product;

@WebService(endpointInterface="sklep.soap.Sklep",
		targetNamespace=Sklep.NAMESPACE,
		serviceName="SklepService",
		portName="SklepPort")
//@MTOM
public class SklepImpl implements Sklep {
	
	public List<Product> readAll() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			ProductDAO productDAO = db.productDAO();
			return productDAO.readAll();
		}
	}

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

    public void savePhoto(int productId, byte[] bytes) {
        PhotoUtil.writeBytes(productId, bytes);
    }
}
