package com.braintreeocc.converters.populators;

import com.braintree.hybris.data.ws.ApplePayAddressWsDTO;
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;

public class BraintreeApplePayAddressPopulator implements Populator<ApplePayAddressWsDTO, AddressData> {

    private BraintreePayPalAddressDetailValidator payPalAddressDetailValidator;

    @Override
    public void populate(ApplePayAddressWsDTO applePayAddress, AddressData addressData) throws ConversionException {
        final boolean isCountryIsoCodeValid = getPayPalAddressDetailValidator()
            .validatePayPalCountryCode(applePayAddress.getCountryCode());
        final boolean isRegionIsoCodeValid = getPayPalAddressDetailValidator()
            .validatePayPalRegionCode(applePayAddress.getCountryCode(), applePayAddress.getAdministrativeArea());

        addressData.setBillingAddress(Boolean.TRUE);
        addressData.setLine1(applePayAddress.getAddressLines().get(0));
        if (applePayAddress.getAddressLines().size() > 1 && applePayAddress.getAddressLines().get(1) != null) {
            addressData.setLine2(applePayAddress.getAddressLines().get(1));
        }
        addressData.setPostalCode(applePayAddress.getPostalCode());
        addressData.setTown(applePayAddress.getLocality());
        if (isCountryIsoCodeValid) {
            final CountryData country = new CountryData();
            country.setIsocode(applePayAddress.getCountryCode());
            addressData.setCountry(country);
        }

        if (isRegionIsoCodeValid) {
            final RegionData region = new RegionData();
            region.setIsocode(applePayAddress.getCountryCode() + "-" + applePayAddress.getAdministrativeArea());
            addressData.setRegion(region);
        }
        addressData.setFirstName(applePayAddress.getGivenName());
        addressData.setLastName(applePayAddress.getFamilyName());
    }

    public BraintreePayPalAddressDetailValidator getPayPalAddressDetailValidator() {
        return payPalAddressDetailValidator;
    }

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