package cn.teammodel.callAble;

import cn.teammodel.model.entity.school.LessonRecord;
import cn.teammodel.repository.LessonRecordRepository;
import com.azure.spring.data.cosmos.core.query.CosmosPageRequest;
import org.springframework.data.domain.Slice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class LessonRecordQueryTask implements Callable<List<LessonRecord>> {
    private final LessonRecordRepository repository;
    private final String lessonRecordKey;
    private final Long startTime;
    private final Long endTime;
    private final String subjectId;
    private final String tmdId;
    private final String grade;
    private final String periodId;
    private static final int SLICE_SIZE = 1000;

    public LessonRecordQueryTask(LessonRecordRepository repository, String lessonRecordKey,
                                 long startTime, long endTime,
                                 String subjectId, String tmdId, String grade,
                                 String periodId) {
        this.repository = repository;
        this.lessonRecordKey = lessonRecordKey;
        this.startTime = startTime;
        this.endTime = endTime;
        this.subjectId = subjectId;
        this.tmdId = tmdId;
        this.grade = grade;
        this.periodId = periodId;
    }

    @Override
    public List<LessonRecord> call() throws Exception {
        List<LessonRecord> result = new ArrayList<>();
        CosmosPageRequest pageRequest = new CosmosPageRequest(0, SLICE_SIZE, null);

        while (true) {
            Slice<LessonRecord> slice = repository.getLessonsByConditions(
                    lessonRecordKey, startTime, endTime, subjectId, tmdId, grade, periodId, pageRequest
            );
            result.addAll(slice.getContent());

            if (!slice.hasNext()) {
                break;
            }
            pageRequest = (CosmosPageRequest) slice.nextPageable();
        }

        return result;
    }
}
