/**
 *
 */
package com.braintreeocc.converters.populators;

import com.braintree.hybris.data.ws.SrcAddressWsDTO;
import com.braintree.paypal.validator.BraintreePayPalAddressDetailValidator;
import de.hybris.platform.commercefacades.user.data.AddressData;
import de.hybris.platform.commercefacades.user.data.CountryData;
import de.hybris.platform.commercefacades.user.data.RegionData;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;

/**
 * Populates AddressData from SrcAddressWsDTO.
 */
public class BraintreeSrcAddressPopulator implements Populator<SrcAddressWsDTO, AddressData> {

    private BraintreePayPalAddressDetailValidator payPalAddressDetailValidator;

    @Override
    public void populate(SrcAddressWsDTO srcAddress, AddressData addressData) throws ConversionException {
        final boolean isCountryIsoCodeValid = payPalAddressDetailValidator
            .validatePayPalCountryCode(srcAddress.getCountryCode());
        final boolean isRegionIsoCodeValid = payPalAddressDetailValidator
            .validatePayPalRegionCode(srcAddress.getCountryCode(), srcAddress.getRegion());

        addressData.setBillingAddress(Boolean.TRUE);
        addressData.setLine1(srcAddress.getStreetAddress());
        addressData.setPhone(srcAddress.getPhoneNumber());
        addressData.setPostalCode(srcAddress.getPostalCode());
        addressData.setTown(srcAddress.getLocality());
        if (isCountryIsoCodeValid) {
            final CountryData country = new CountryData();
            country.setIsocode(srcAddress.getCountryCode());
            addressData.setCountry(country);
        }

        if (isRegionIsoCodeValid) {
            final RegionData region = new RegionData();
            region.setIsocode(srcAddress.getCountryCode() + "-" + srcAddress.getRegion());
            addressData.setRegion(region);
        }

        addressData.setFirstName(srcAddress.getFirstName());
        addressData.setLastName(srcAddress.getLastName());
    }

    public void setPayPalAddressDetailValidator(BraintreePayPalAddressDetailValidator payPalAddressDetailValidator) {
        this.payPalAddressDetailValidator = payPalAddressDetailValidator;
    }

}
