package com.braintree.customersupportbackoffice.populators.transaction;

import com.braintree.command.result.BrainTreeAbstractTransactionResult;
import com.braintree.converters.utils.BraintreeTransactionConverterUtils;
import com.braintree.hybris.data.BrainTreeResponseResultData;
import com.braintree.hybris.data.BraintreeTransactionEntryData;
import com.braintree.hybris.data.BraintreeTransactionEntryDetailData;
import com.braintreegateway.Transaction;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;

public class BrainTreeTransactionAdditionalPopulator implements
    Populator<BrainTreeAbstractTransactionResult, BrainTreeResponseResultData> {

    @Override
    public void populate(BrainTreeAbstractTransactionResult source, BrainTreeResponseResultData target)
        throws ConversionException {
        final Transaction transaction = source.getTransaction();
        if (transaction != null) {
            final BraintreeTransactionEntryData braintreeTransactionEntryData = new BraintreeTransactionEntryData();
            braintreeTransactionEntryData.setId(transaction.getId());
            braintreeTransactionEntryData
                .setDate(formatDate(transaction));
            braintreeTransactionEntryData
                .setPaymentInfo(BraintreeTransactionConverterUtils.formedPaymentInfo(transaction));
            braintreeTransactionEntryData.setAmount(BraintreeTransactionConverterUtils
                .formedAmount(transaction.getAmount(), transaction.getCurrencyIsoCode()));

            if (transaction.getCustomer() != null) {
                braintreeTransactionEntryData.setCustomer(BraintreeTransactionConverterUtils
                        .formedName(transaction.getCustomer().getFirstName(), transaction.getCustomer().getLastName()));
            }
            if (transaction.getStatus() != null) {
                braintreeTransactionEntryData.setStatus(transaction.getStatus().name());
            }
            if (transaction.getType() != null) {
                braintreeTransactionEntryData.setType(transaction.getType().name());
            }
            braintreeTransactionEntryData.setDetails(convertDetails(transaction));
            target.setTransactionEntryData(braintreeTransactionEntryData);
        }
    }

    protected BraintreeTransactionEntryDetailData convertDetails(Transaction transaction) {
        return BraintreeTransactionConverterUtils.convertDetails(transaction);
    }

    protected String formatDate(Transaction transaction) {
        return BraintreeTransactionConverterUtils.formedDate(transaction.getCreatedAt());
    }

}
