package com.braintree.strategy.impl;

import de.hybris.platform.commerceservices.stock.CommerceStockService;
import de.hybris.platform.core.model.order.AbstractOrderEntryModel;
import de.hybris.platform.ordersplitting.model.ConsignmentModel;
import de.hybris.platform.ordersplitting.strategy.AbstractSplittingStrategy;


public class BrainTreeSplitByAvailableCount extends AbstractSplittingStrategy {

    private CommerceStockService commerceStockService;

    @Override
    public Object getGroupingObject(final AbstractOrderEntryModel orderEntry) {
        if (orderEntry.getDeliveryPointOfService() != null) {
            final Long stock = commerceStockService
                    .getStockLevelForProductAndPointOfService(orderEntry.getProduct(),
                            orderEntry.getDeliveryPointOfService());
            return Boolean.valueOf(stock == null || stock.longValue() >= orderEntry.getQuantity().longValue());
        } else {
            Long stock = Long.valueOf(0);
            if (orderEntry.getOrder().getStore() != null) {
                stock = commerceStockService.getStockLevelForProductAndBaseStore(orderEntry.getProduct(),
                        orderEntry.getOrder().getStore());
            }
            return Boolean.valueOf(stock == null || stock.longValue() >= orderEntry.getQuantity().longValue());
        }
    }

    @Override
    public void afterSplitting(final Object groupingObject, final ConsignmentModel createdOne) {
        //nothing to do
    }

    public void setCommerceStockService(final CommerceStockService commerceStockService) {
        this.commerceStockService = commerceStockService;
    }

}
