package com.braintreeocc.converters;

import com.braintree.hybris.data.ws.PayPalAddressWsDTO;
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.servicelayer.dto.converter.Converter;
import org.apache.commons.lang.StringUtils;

public class BraintreePayPalAddressConverterForOCC implements Converter<PayPalAddressWsDTO, AddressData> {

    private BraintreePayPalAddressDetailValidator payPalAddressDetailValidator;

    public AddressData convert(final PayPalAddressWsDTO address) {
        final AddressData addressData = new AddressData();
        return convert(address, addressData);
    }


    public AddressData convert(final PayPalAddressWsDTO address, final AddressData addressData) {
        final boolean isCountryIsoCodeValid = payPalAddressDetailValidator
                .validatePayPalCountryCode(address.getCountryCode());
        final boolean isRegionIsoCodeValid = payPalAddressDetailValidator
                .validatePayPalRegionCode(address.getCountryCode(), address.getState());
        if (isCountryIsoCodeValid) {
            final CountryData country = new CountryData();
            country.setIsocode(address.getCountryCode());
            addressData.setCountry(country);
        }

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

        if (StringUtils.isBlank(address.getRecipientName())) {
            addressData.setFirstName(StringUtils.EMPTY);
            addressData.setLastName(StringUtils.EMPTY);
        } else {
            final String[] split = address.getRecipientName().split(" ");
            String firstName = StringUtils.EMPTY;
            String lastName = StringUtils.EMPTY;
            if (split.length == 1) {
                firstName = split[0];
            }
            if (split.length >= 2) {
                firstName = split[0];
                lastName = split[1];
            }
            addressData.setFirstName(firstName);
            addressData.setLastName(lastName);
        }
        addressData.setLine1(address.getLine1());
        addressData.setLine2(address.getLine2());
        addressData.setPostalCode(address.getPostalCode());
        addressData.setTown(address.getCity());

        return addressData;
    }

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