package com.braintree.converters;

import com.braintree.hybris.data.UsBankAccountAddressData;
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.ConversionException;
import de.hybris.platform.servicelayer.dto.converter.Converter;

import java.util.Optional;


public class BrainTreeUsBankAccountAddressDataConverter implements Converter<UsBankAccountAddressData, AddressData> {

    @Override
    public AddressData convert(UsBankAccountAddressData usBankAccountAddressData) throws ConversionException {
        final AddressData addressData = new AddressData();
        return convert(usBankAccountAddressData, addressData);
    }

    @Override
    public AddressData convert(UsBankAccountAddressData usBankAccountAddressData, AddressData addressData) throws ConversionException {
        Optional.ofNullable(usBankAccountAddressData.getBusinessName())
                .ifPresentOrElse(businessName -> addressData.setFirstName(businessName), () -> {
                    addressData.setFirstName(usBankAccountAddressData.getFirstName());
                    addressData.setLastName(usBankAccountAddressData.getLastName());
                });
        addressData.setLine1(usBankAccountAddressData.getLine1());
        if (usBankAccountAddressData.getLine2() != null) {
            addressData.setLine2(usBankAccountAddressData.getLine2());
        }
        addressData.setTown(usBankAccountAddressData.getCity());
        addressData.setPostalCode(usBankAccountAddressData.getPostalCode());

        CountryData countryData = new CountryData();
        countryData.setIsocode(usBankAccountAddressData.getCountryCode());

        RegionData regionData = new RegionData();
        regionData.setIsocode(countryData.getIsocode() + "-" + usBankAccountAddressData.getState());

        addressData.setCountry(countryData);
        addressData.setRegion(regionData);
        return addressData;
    }
}
