package com.braintreeocc.converters.populators;

import com.braintree.hybris.data.ws.GooglePayAddressWsDTO;
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 BraintreeGooglePayAddressPopulator implements Populator<GooglePayAddressWsDTO, AddressData> {

    private BraintreePayPalAddressDetailValidator payPalAddressDetailValidator;

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

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

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

        if(googlePayAddress.getName() != null){
            final String[] names = googlePayAddress.getName().split(" ", 2);
            addressData.setLastName(names[0]);
            if (names.length > 1) {
                addressData.setFirstName(names[1]);
            }
        }

    }

    public BraintreePayPalAddressDetailValidator getPayPalAddressDetailValidator() {
        return payPalAddressDetailValidator;
    }

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