package ru.yandex.direct.api.v5.entity.ads.converter;

import java.util.Collection;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

import com.yandex.direct.api.v5.ads.ObjectFactory;
import com.yandex.direct.api.v5.ads.TrackingPixelGetArray;

import ru.yandex.direct.core.entity.banner.type.pixels.PixelProvider;

import static java.util.stream.Collectors.toList;
import static ru.yandex.direct.utils.CommonUtils.ifNotNull;
import static ru.yandex.direct.utils.CommonUtils.nvl;

@ParametersAreNonnullByDefault
class TrackingPixelsConverter {

    private static final ObjectFactory FACTORY = new ObjectFactory();
    public static final String UNKNOWN_PROVIDER_NAME = "Unknown";

    @Nullable
    static TrackingPixelGetArray convertTrackingPixels(@Nullable Collection<String> pixels) {
        if (pixels == null || pixels.isEmpty()) {
            return null;
        }

        return FACTORY.createTrackingPixelGetArray().withItems(
                pixels.stream()
                        .map(pixelUrl -> {
                            String providerName = ifNotNull(PixelProvider.fromUrl(pixelUrl), PixelProvider::getProviderName);
                            return FACTORY.createTrackingPixelGetItem()
                                    .withTrackingPixel(pixelUrl)
                                    .withProvider(nvl(providerName, UNKNOWN_PROVIDER_NAME));
                        })
                        .collect(toList()));
    }
}
