package ctbrec.ui.sites.streamray;

import ctbrec.Model;
import ctbrec.sites.streamray.Streamray;
import ctbrec.sites.streamray.StreamrayModel;
import javafx.concurrent.Task;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Slf4j
public class StreamrayFavoritesService extends AbstractStreamrayUpdateService {

    public StreamrayFavoritesService(Streamray site) {
        super(site);
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<>() {
            @Override
            public List<Model> call() throws IOException {
                return getModelList().stream()
                        .skip((page - 1) * (long) modelsPerPage)
                        .limit(modelsPerPage)
                        .map(Model.class::cast)
                        .toList();
            }
        };
    }

    private List<StreamrayModel> getModelList() throws IOException {
        List<StreamrayModel> models = site.loadModelList(true).stream().filter(StreamrayModel::isFavorite).toList();
        if (models == null) {
            models = Collections.emptyList();
        }
        return models;
    }
}
