package com.braintree.order.service.impl;

import com.braintree.helpers.OrderVoidHelper;
import com.braintree.order.service.BraintreeOrderBackofficeUtilService;
import de.hybris.platform.core.enums.OrderStatus;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;

import java.util.function.Predicate;

public class DefaultBraintreeOrderBackofficeUtilService implements BraintreeOrderBackofficeUtilService {

    private OrderVoidHelper orderVoidHelper;

    @Override
    public boolean isOrderAmountCaptured(final OrderModel order) {
        Predicate<PaymentTransactionEntryModel> filterEntries = entry -> orderVoidHelper.isSuccessfulCaptureTransaction(entry);

        double capturedSum = order.getPaymentTransactions().stream()
                .flatMap(transaction -> transaction.getEntries().stream().filter(filterEntries))
                .mapToDouble(entry -> entry.getAmount().doubleValue()).sum();

        return capturedSum >= order.getTotalPrice();
    }

    @Override
    public boolean isOrderVoided(final OrderModel order) {
        return OrderStatus.CANCELLED.equals(order.getStatus());
    }

    @Override
    public boolean paidByCard(final OrderModel order) {
        boolean paidByCard = false;
        Object cardType = order.getPaymentInfo().getProperty("cardType");
        if (cardType != null) {
            paidByCard = true;
        }
        return paidByCard;
    }

    public void setOrderVoidHelper(OrderVoidHelper orderVoidHelper) {
        this.orderVoidHelper = orderVoidHelper;
    }

}
