package ctbrec.ui.sites.streamray;

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

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.function.Predicate;

@Slf4j
public class StreamrayUpdateService extends AbstractStreamrayUpdateService {

    private List<StreamrayModel> models;
    private Instant lastListInfoRequest = Instant.EPOCH;

    @Setter
    protected Predicate<StreamrayModel> filter;

    public StreamrayUpdateService(Streamray site, Predicate<StreamrayModel> filter) {
        super(site);
        this.filter = filter;
    }

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

    private List<StreamrayModel> getModels() throws IOException {
        if (models == null || Duration.between(lastListInfoRequest, Instant.now()).getSeconds() >= 10) {
            models = site.loadModelList();
            lastListInfoRequest = Instant.now();
        }
        return models;
    }
}
