@NonNull
 private List<FeedItem> getCandidates() {
   List<FeedItem> candidates = new ArrayList<>();
   List<FeedItem> downloadedItems = DBReader.getDownloadedItems();
   Calendar cal = Calendar.getInstance();
   cal.add(Calendar.DAY_OF_MONTH, -1 * numberOfDaysAfterPlayback);
   Date mostRecentDateForDeletion = cal.getTime();
   for (FeedItem item : downloadedItems) {
     if (item.hasMedia()
         && item.getMedia().isDownloaded()
         && !item.isTagged(FeedItem.TAG_QUEUE)
         && item.isPlayed()
         && !item.isTagged(FeedItem.TAG_FAVORITE)) {
       FeedMedia media = item.getMedia();
       // make sure this candidate was played at least the proper amount of days prior
       // to now
       if (media != null
           && media.getPlaybackCompletionDate() != null
           && media.getPlaybackCompletionDate().before(mostRecentDateForDeletion)) {
         candidates.add(item);
       }
     }
   }
   return candidates;
 }
  public void testSetFeedMediaPlaybackInformation()
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    final int POSITION = 50;
    final long LAST_PLAYED_TIME = 1000;
    final int PLAYED_DURATION = 60;
    final int DURATION = 100;

    Feed feed = new Feed("url", null, "title");
    List<FeedItem> items = new ArrayList<>();
    feed.setItems(items);
    FeedItem item = new FeedItem(0, "Item", "Item", "url", new Date(), FeedItem.PLAYED, feed);
    items.add(item);
    FeedMedia media =
        new FeedMedia(
            0, item, DURATION, 1, 1, "mime_type", "dummy path", "download_url", true, null, 0, 0);
    item.setMedia(media);

    DBWriter.setFeedItem(item).get(TIMEOUT, TimeUnit.SECONDS);

    media.setPosition(POSITION);
    media.setLastPlayedTime(LAST_PLAYED_TIME);
    media.setPlayedDuration(PLAYED_DURATION);

    DBWriter.setFeedMediaPlaybackInformation(item.getMedia()).get(TIMEOUT, TimeUnit.SECONDS);

    FeedItem itemFromDb = DBReader.getFeedItem(item.getId());
    FeedMedia mediaFromDb = itemFromDb.getMedia();

    assertEquals(POSITION, mediaFromDb.getPosition());
    assertEquals(LAST_PLAYED_TIME, mediaFromDb.getLastPlayedTime());
    assertEquals(PLAYED_DURATION, mediaFromDb.getPlayedDuration());
    assertEquals(DURATION, mediaFromDb.getDuration());
  }
  @Override
  public int performCleanup(Context context, int numberOfEpisodesToDelete) {
    List<FeedItem> candidates = getCandidates();
    List<FeedItem> delete;

    Collections.sort(
        candidates,
        (lhs, rhs) -> {
          Date l = lhs.getMedia().getPlaybackCompletionDate();
          Date r = rhs.getMedia().getPlaybackCompletionDate();

          if (l == null) {
            l = new Date();
          }
          if (r == null) {
            r = new Date();
          }
          return l.compareTo(r);
        });

    if (candidates.size() > numberOfEpisodesToDelete) {
      delete = candidates.subList(0, numberOfEpisodesToDelete);
    } else {
      delete = candidates;
    }

    for (FeedItem item : delete) {
      try {
        DBWriter.deleteFeedMediaOfItem(context, item.getMedia().getId()).get();
      } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
      }
    }

    int counter = delete.size();

    Log.i(
        TAG,
        String.format(
            "Auto-delete deleted %d episodes (%d requested)", counter, numberOfEpisodesToDelete));

    return counter;
  }
  public void testDeleteFeedNoDownloadedFiles()
      throws ExecutionException, InterruptedException, TimeoutException {
    File destFolder = getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER);
    assertNotNull(destFolder);

    Feed feed = new Feed("url", null, "title");
    feed.setItems(new ArrayList<>());

    // create Feed image
    File imgFile = new File(destFolder, "image");
    FeedImage image = new FeedImage(0, "image", imgFile.getAbsolutePath(), "url", true);
    image.setOwner(feed);
    feed.setImage(image);

    List<File> itemFiles = new ArrayList<>();
    // create items with downloaded media files
    for (int i = 0; i < 10; i++) {
      FeedItem item =
          new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed);
      feed.getItems().add(item);

      File enc = new File(destFolder, "file " + i);
      itemFiles.add(enc);

      FeedMedia media =
          new FeedMedia(
              0,
              item,
              1,
              1,
              1,
              "mime_type",
              enc.getAbsolutePath(),
              "download_url",
              false,
              null,
              0,
              0);
      item.setMedia(media);
    }

    PodDBAdapter adapter = PodDBAdapter.getInstance();
    adapter.open();
    adapter.setCompleteFeed(feed);
    adapter.close();

    assertTrue(feed.getId() != 0);
    assertTrue(feed.getImage().getId() != 0);
    for (FeedItem item : feed.getItems()) {
      assertTrue(item.getId() != 0);
      assertTrue(item.getMedia().getId() != 0);
    }

    DBWriter.deleteFeed(getInstrumentation().getTargetContext(), feed.getId())
        .get(TIMEOUT, TimeUnit.SECONDS);

    adapter = PodDBAdapter.getInstance();
    adapter.open();
    Cursor c = adapter.getFeedCursor(feed.getId());
    assertTrue(c.getCount() == 0);
    c.close();
    c = adapter.getImageCursor(String.valueOf(image.getId()));
    assertTrue(c.getCount() == 0);
    c.close();
    for (FeedItem item : feed.getItems()) {
      c = adapter.getFeedItemCursor(String.valueOf(item.getId()));
      assertTrue(c.getCount() == 0);
      c.close();
      c = adapter.getSingleFeedMediaCursor(item.getMedia().getId());
      assertTrue(c.getCount() == 0);
      c.close();
    }
    adapter.close();
  }