package com.braintree.converters.populators;

import com.braintree.enums.ExpirationStatus;
import com.braintree.model.BrainTreePaymentInfoModel;
import com.braintree.util.BrainTreeUtils;
import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData;
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 de.hybris.platform.servicelayer.dto.converter.Converter;


public class BrainTreePaymentInfoPopulator implements Populator<BrainTreePaymentInfoModel, CCPaymentInfoData> {

    private Converter<AddressModel, AddressData> addressConverter;

    @Override
    public void populate(final BrainTreePaymentInfoModel source, final CCPaymentInfoData target)
            throws ConversionException {
        target.setId(source.getPk().toString());
        target.setCardNumber(source.getCardNumber());
        target.setExpiryMonth(source.getExpirationMonth());
        target.setExpiryYear(source.getExpirationYear());
        target.setExpirationStatus(source.getExpirationStatus().getCode());
        target.setAccountHolderName(source.getImageSource());
        target.setSubscriptionId(source.getPaymentProvider());
        target.setPaypalFundingSource(source.getPaypalFundingSource());
        target.setSaved(source.isSaved());
        target.setPaymentMethodToken(source.getPaymentMethodToken());
        target.setCardholderName(source.getCardholderName());
        target.setPayer(source.getPayer());
        target.setPaymentMethodNonce(source.getNonce());
        target.setCustomerId(source.getCustomerId());
        target.setLast4(source.getLast4());
        target.setRoutingNumber(source.getRoutingNumber());

        if (source.getCardType() != null) {
            target.setCardType(source.getCardType().toString());
        }

        if (BrainTreeUtils.isCreditCardPayment(source.getPaymentProvider())
                && source.getExpirationStatus().equals(ExpirationStatus.EXPIRE_SOON)) {
            target.setReminderMonthToExpire(BrainTreeUtils.getReminderMonthToExpire(source) + 1);
        }

        if (source.getBillingAddress() != null) {
            target.setBillingAddress(getAddressConverter().convert(source.getBillingAddress()));
        }
    }

    public Converter<AddressModel, AddressData> getAddressConverter() {
        return addressConverter;
    }

    public void setAddressConverter(final Converter<AddressModel, AddressData> addressConverter) {
        this.addressConverter = addressConverter;
    }

}
