package com.braintree.populators;

import com.braintree.command.result.BrainTreeBillingAddressResult;
import com.braintree.command.result.BrainTreePaymentMethodResult;
import com.braintree.enums.BrainTreeCardType;
import com.braintree.model.BrainTreePaymentInfoModel;
import com.braintree.util.BrainTreeUtils;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.user.AddressModel;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import de.hybris.platform.servicelayer.dto.converter.Converter;

/**
 * Populates BrainTreePaymentInfoModel from BrainTreePaymentMethodResult.
 */
public class BraintreeGraphQLPaymentMethodPopulator implements
        Populator<BrainTreePaymentMethodResult, BrainTreePaymentInfoModel> {

    private Converter<BrainTreeBillingAddressResult, AddressModel> braintreeAddressConverter;

    @Override
    public void populate(BrainTreePaymentMethodResult result, BrainTreePaymentInfoModel model)
            throws ConversionException {
        if (result != null && model != null) {
            model.setPaymentMethodToken(result.getPaymentMethodToken());
            model.setPaymentMethodGraphQLToken(result.getPaymentMethodGraphQLToken());
            model.setImageSource(result.getImageSource());
            model.setPaymentProvider(result.getPaymentProvider());

            if (BrainTreeUtils.isPayPalPayment(result.getPaymentProvider())) {
                model.setPaymentInfo(result.getEmail());
            } else if (result.getBin() != null && result.getLast4() != null) {
                final String number = String.format("%s******%s", result.getBin(), result.getLast4());
                model.setPaymentInfo(number);
                model.setCardNumber(number);
            }

            model.setCreatedAt(result.getCreatedAt().getTime());
            model.setCustomerId(result.getCustomerId());
            if (result.getCardType() != null) {
                model.setCardType(BrainTreeCardType.valueOf(result.getCardType()));
            }
            model.setCardholderName(result.getCardholderName());
            model.setExpirationMonth(result.getExpirationMonth());
            model.setExpirationYear(result.getExpirationYear());

            if (result.getBillingAddressResult() != null) {
                model.setBillingAddress(getBraintreeAddressConverter().convert(result.getBillingAddressResult()));
            }
        }
    }

    public Converter<BrainTreeBillingAddressResult, AddressModel> getBraintreeAddressConverter() {
        return braintreeAddressConverter;
    }

    public void setBraintreeAddressConverter(
            Converter<BrainTreeBillingAddressResult, AddressModel> braintreeAddressConverter) {
        this.braintreeAddressConverter = braintreeAddressConverter;
    }
}
