package com.airlock.iam.oauth2.domain.service.repositor;

import com.airlock.iam.oauth2.domain.service.repository.OAuth2CleanupRepository;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BatchedOrphanedSessionsProvider implements OAuth2CleanupRepository.OrphanedSessionsProvider {
   private final OAuth2CleanupRepository cleanupRepository;
   private final int batchSize;
   private List<Long> sessionPks;
   private int index;

   @Override
   public List<Long> getNextOrphanedSessionPksBatch() {
      this.ensureEntriesLoaded();
      List<Long> result = Collections.unmodifiableList(this.sessionPks.subList(this.index, Math.min(this.index + this.batchSize, this.sessionPks.size())));
      this.index = this.index + result.size();
      return result;
   }

   @Override
   public int getTotalNumberOfSessionsToDelete() {
      this.ensureEntriesLoaded();
      return this.sessionPks.size();
   }

   @Override
   public boolean hasMoreSessions() {
      this.ensureEntriesLoaded();
      return this.index < this.sessionPks.size();
   }

   private void ensureEntriesLoaded() {
      if (this.sessionPks == null) {
         this.sessionPks = Arrays.asList(this.cleanupRepository.getOrphanSessionPks());
      }
   }

   @SuppressFBWarnings(justification = "generated code")
   public BatchedOrphanedSessionsProvider(OAuth2CleanupRepository cleanupRepository, int batchSize) {
      this.cleanupRepository = cleanupRepository;
      this.batchSize = batchSize;
   }
}
