package io.delphiplatform.api.v3.bigtable.processing;

import com.sonymusic.delphi.etl.apps.proto.Tiktok;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;

import io.delphiplatform.api.util.CollectionUtils;
import io.delphiplatform.api.v3.bigtable.entity.TikTokTrackCountryMetrics;
import io.delphiplatform.api.v3.bigtable.entity.TikTokTrackMetrics;
import io.delphiplatform.api.v3.constant.CountryCodeConstant;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TikTokTrackMetricsConverter {

    public Stream<TikTokTrackCountryMetrics> convert(Stream<TikTokTrackMetrics> trackMetrics,
        Set<String> countryCodes) {

        return trackMetrics
            .flatMap(metrics -> metrics.getStats().getCountriesMap().entrySet().stream()
                .filter(getCountryPredicate(countryCodes))
                .map(countryStats -> {
                    TikTokTrackCountryMetrics countryMetrics = new TikTokTrackCountryMetrics();
                    countryMetrics.setDate(metrics.getDate());
                    countryMetrics.setIsrc(metrics.getIsrc());
                    countryMetrics.setContentType(metrics.getContentType());
                    countryMetrics.setCountryCode(countryStats.getKey());
                    countryMetrics.setStats(countryStats.getValue());
                    return countryMetrics;
                }));
    }

    private Predicate<Map.Entry<String, Tiktok.TikTokStats>> getCountryPredicate(Set<String> countryCodes) {
        Predicate<Map.Entry<String, Tiktok.TikTokStats>> countryPredicate = elem -> (CollectionUtils
            .contains(countryCodes, elem.getKey()));
        Predicate<Map.Entry<String, Tiktok.TikTokStats>> notWwPredicate = elem -> (!CountryCodeConstant.WORLDWIDE
            .equalsIgnoreCase(elem.getKey()));

        return CollectionUtils.isEmpty(countryCodes) ? notWwPredicate : countryPredicate;
    }
}
