package com.braintree.converters.populators;

import com.braintree.model.BrainTreePaymentInfoModel;
import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData;
import de.hybris.platform.commercefacades.user.converters.populator.AddressReversePopulator;
import de.hybris.platform.commercefacades.user.data.AddressData;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.user.AddressModel;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import org.springframework.util.Assert;

public class BraintreePaymentInfoReversePopulator implements Populator<CCPaymentInfoData, BrainTreePaymentInfoModel> {

    private static final String COMA_SEPARATOR = ", ";

    private AddressReversePopulator addressReversePopulator;
    @Override
    public void populate(final CCPaymentInfoData ccPaymentInfoData,
                         final BrainTreePaymentInfoModel brainTreePaymentInfoModel)
            throws ConversionException {

        Assert.notNull(ccPaymentInfoData, "Parameter ccPaymentInfoData cannot be null.");
        Assert.notNull(brainTreePaymentInfoModel, "Parameter creditCardPaymentInfoModel cannot be null.");

        brainTreePaymentInfoModel.setCardNumber(ccPaymentInfoData.getCardNumber());
        brainTreePaymentInfoModel.setExpirationYear(ccPaymentInfoData.getExpiryYear());
        brainTreePaymentInfoModel.setExpirationMonth(ccPaymentInfoData.getExpiryMonth());

        brainTreePaymentInfoModel.setImageSource(ccPaymentInfoData.getAccountHolderName());
        brainTreePaymentInfoModel.setCardholderName(ccPaymentInfoData.getCardholderName());
        brainTreePaymentInfoModel.setPaymentProvider(ccPaymentInfoData.getSubscriptionId());
        brainTreePaymentInfoModel.setSaved(ccPaymentInfoData.isSaved());
        brainTreePaymentInfoModel.setPaymentMethodToken(ccPaymentInfoData.getPaymentMethodToken());
        brainTreePaymentInfoModel.setPayer(ccPaymentInfoData.getPayer());
        brainTreePaymentInfoModel.setNonce(ccPaymentInfoData.getPaymentMethodNonce());

        final AddressData billingAddressData = ccPaymentInfoData.getBillingAddress();
        final AddressModel billingAddressModel = brainTreePaymentInfoModel.getBillingAddress();
        if (billingAddressData != null && billingAddressModel != null) {
            getAddressReversePopulator().populate(billingAddressData, billingAddressModel);

            if (COMA_SEPARATOR.equals(billingAddressModel.getLastname())) {
                billingAddressModel.setLastname(null);
            }
        }

    }

    public AddressReversePopulator getAddressReversePopulator() {
        return addressReversePopulator;
    }

    public void setAddressReversePopulator(AddressReversePopulator addressReversePopulator) {
        this.addressReversePopulator = addressReversePopulator;
    }
}
