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

import com.sonymusic.delphi.etl.apps.proto.TiktokSound.TikTokSound;
import com.sonymusic.delphi.etl.apps.proto.TiktokSound.TikTokTopSounds;

import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import io.delphiplatform.api.util.model.ModelUtils;
import io.delphiplatform.api.v3.bigtable.entity.TikTokTopIsrcSoundsEntity;
import io.delphiplatform.api.v3.model.tiktok.TikTokContentType;
import io.delphiplatform.api.v3.model.tiktok.top.sound.TikTokTopIsrcSound;

@Service
public class TikTokTopIsrcSoundsConverter {

    public Stream<TikTokTopIsrcSound> convert(Stream<TikTokTopIsrcSoundsEntity> models) {

        List<TikTokTopIsrcSoundsEntity> modelsList = models.collect(Collectors.toList());

        Map<LocalDate, Long> isrcTotalCreations = modelsList.stream()
            .filter(m -> m.getTopSounds() != null)
            .collect(Collectors.toMap(TikTokTopIsrcSoundsEntity::getDate,
                m -> m.getTopSounds().getSoundsMap().values()
                    .stream()
                    .max(Comparator.comparing(TikTokSound::getCreations))
                    .map(topSound -> ModelUtils.calculateTotalIsrcCreations(topSound.getCreations(), topSound.getCreationsShare()))
                    .orElse(0L), Long::sum));

        return modelsList.stream().flatMap(entity -> {
            TikTokTopSounds topSounds = entity.getTopSounds();
            if (topSounds == null) {
                return Stream.empty();
            }
            return topSounds.getSoundsMap().values().stream().map(tikTokTopSound -> {
                TikTokTopIsrcSound model = new TikTokTopIsrcSound();

                model.setReportDate(entity.getDate());
                model.setSoundId(tikTokTopSound.getSoundId());
                model.setIsrcs(Set.of(entity.getIsrc()));
                model.setContentType(TikTokContentType.fromValue(tikTokTopSound.getContentType()));
                model.setCreations(tikTokTopSound.getCreations());
                model.setTotalIsrcCreations(isrcTotalCreations.get(entity.getDate()));

                return model;
            });
        });
    }

}
