package com.braintree.populators;

import com.braintree.command.result.BrainTreeRefundTransactionResult;
import com.braintree.command.result.BrainTreeTransactionResult;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeExchangeLegacyIdRequest;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeRefund;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeTransaction;
import com.braintree.method.BrainTreePaymentService;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import de.hybris.platform.servicelayer.dto.converter.Converter;

import java.math.BigDecimal;

import static com.braintree.constants.BraintreeConstants.TYPE_TRANSACTION_PARAMETER;

public class BraintreeTransactionToBraintreeTransactionResultPopulator implements
        Populator<BrainTreeTransaction, BrainTreeTransactionResult> {

    private Converter<BrainTreeRefund, BrainTreeRefundTransactionResult> refundTransactionResultConverter;
    private BrainTreePaymentService brainTreePaymentService;

    @Override
    public void populate(BrainTreeTransaction braintreeTransaction, BrainTreeTransactionResult braintreeTransactionResult)
            throws ConversionException {
        braintreeTransactionResult.setStatus(braintreeTransaction.getStatus().name());
        braintreeTransactionResult.setRefunds(refundTransactionResultConverter.convertAll(braintreeTransaction.getRefunds()));
        braintreeTransactionResult.setTotalAmount(new BigDecimal(braintreeTransaction.getAmount().getValue()));
        braintreeTransactionResult.setId(braintreeTransaction.getLegacyId());

        String graphQLId = getGraphQLId(braintreeTransaction);
        braintreeTransactionResult.setGraphQLId(graphQLId);
    }

    private String getGraphQLId(BrainTreeTransaction braintreeTransaction) {
        BrainTreeExchangeLegacyIdRequest request = new BrainTreeExchangeLegacyIdRequest();
        request.setLegacyId(braintreeTransaction.getLegacyId());
        request.setType(TYPE_TRANSACTION_PARAMETER);
        return brainTreePaymentService.exchangeLegacyIdToGraphQLId(request);
    }

    public void setRefundTransactionResultConverter(Converter<BrainTreeRefund, BrainTreeRefundTransactionResult>
                                                            refundTransactionResultConverter) {
        this.refundTransactionResultConverter = refundTransactionResultConverter;
    }

    public void setBrainTreePaymentService(BrainTreePaymentService brainTreePaymentService) {
        this.brainTreePaymentService = brainTreePaymentService;
    }

}
