package ru.yandex.canvas.service.video.files;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import ru.yandex.canvas.model.video.files.AudioSource;

import static java.lang.Integer.min;

public class AudioSearch {

    private Map<String, AudioSource> audios;
    private List<AudioSource> allAudios;

    public AudioSearch(Map<String, AudioSource> audios, Map<String, Long> audioOrder) {
        this.audios = audios;

        this.allAudios = audios.values().stream().sorted(Comparator.comparing(e -> audioOrder.get(e.getId())))
                .collect(Collectors.toList());
    }

    public StockMoviesService.SearchResult<AudioSource> search(String nameSubString) {
        return search(nameSubString, allAudios.size(), 0);
    }

    public StockMoviesService.SearchResult<AudioSource> search(String nameSubString, int limit, int offset) {

        List<AudioSource> result;

        if (nameSubString == null) {
            result = allAudios;
        } else {
            result = audios.values().stream().filter(e -> e.getName().contains(nameSubString)).distinct()
                    .collect(Collectors.toList());
        }

        if (result.size() == 0) {
            return new StockMoviesService.SearchResult<>(0, Collections.emptyList());
        }

        int fromIndex = min(offset, result.size() - 1); //0
        int toIndex = min(offset + limit, result.size()); //2

        return new StockMoviesService.SearchResult<>(result.size(), result.subList(fromIndex, toIndex));
    }

}
