package com.braintree.populators;

import com.braintree.command.result.BrainTreeBillingAddressResult;
import com.braintree.hybris.data.graphql.commands.response.BrainTreeAddress;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import org.apache.commons.lang.StringUtils;

import java.util.Objects;

/**
 * Populates BrainTreeBillingAddressResult from BrainTreeAddress.
 */
public class BrainTreeGraphQLAddressToAddressResultPopulator implements Populator<BrainTreeAddress, BrainTreeBillingAddressResult> {
    private static final String SPACE = " ";

    @Override
    public void populate(BrainTreeAddress source, BrainTreeBillingAddressResult addressResult) throws ConversionException {
        if (source != null && addressResult != null) {
            addressResult.setCompany(source.getCompany());
            addressResult.setCountyCode(source.getCountryCode());
            addressResult.setStreetAddress(source.getAddressLine1());
            addressResult.setExtendedAddress(getExtendedAddress(source.getAddressLine2()));
            addressResult.setRegion(source.getAdminArea1());
            addressResult.setLocality(source.getAdminArea2());
            addressResult.setPostalCode(source.getPostalCode());
            addressResult.setPhone(source.getPhoneNumber());
            parseName(source.getFullName(), addressResult);
        }
    }

    private void parseName(String fullName, BrainTreeBillingAddressResult addressResult) {
        if (Objects.nonNull(fullName) && fullName.contains(SPACE)) {
            final String[] parts = fullName.split(SPACE);
            addressResult.setFirstName(parts[0]);
            addressResult.setLastName(parts[1]);
        } else {
            addressResult.setFirstName(fullName);
        }
    }

    private String getExtendedAddress(String addressLine2) {
        if (Objects.isNull(addressLine2)) {
            return StringUtils.EMPTY;
        }
        return addressLine2;
    }
}
