package com.capgemini.reports.optimized;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Folder {
  private final Path path;

  public Folder(Path path) {
    this.path = path;
  }

  public Path mostRecentFile() throws IOException {
    List<Path> files = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
      for (Path file : directoryStream) {
        if (!file.toFile().isDirectory()) {
          files.add(file);
        }
      }
    }

    // Sort newest file is first element
    Collections.sort(files, new Comparator<Path>() {
      public int compare(Path o1, Path o2) {
        try {
          return Files.getLastModifiedTime(o2).compareTo(Files.getLastModifiedTime(o1));
        }
        catch (IOException e) {
          return 0;
        }
      }
    });

    return files.get(0);
  }

  public boolean exist() {
    return path.toFile().exists();
  }

  public boolean isEmpty() throws IOException {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
      return !directoryStream.iterator().hasNext();
    }
  }
}