package mosaiccreator;

import java.io.File;
import java.io.FileFilter;
import java.util.Vector;
import java.util.Enumeration;
import javax.swing.JLabel;

/**
 *
 * <p>Title: File Finder</p>
 * <p>Description: Recusively Finds all the images in the folder passed in </p>
 * @author Lance Finfock
 * @version 1.0
 */
public class FileFinder implements Runnable {

  private File sourceDir; // the starting folder
  private Vector FilesFound; //all the images found
  private JLabel amountFoundLabel; // the display label the count of images found
  private MainWindow returnMethode;

  /**
   *
   * @param folder File the folder where the image are
   * @param label JLabel The lable that displays the number of images found
   * @param frame1 MainWindow the window the call to this program came from and will return to
   */
  public FileFinder(File folder,
                    JLabel label,
                    MainWindow frame1) {
    this.FilesFound = new Vector();
    this.sourceDir = folder;
    this.returnMethode = frame1;
    this.amountFoundLabel = label;

    //start the thread in this class
    new Thread(this).start();
  }

  public void run() {

    findfiles(sourceDir);

    //storing the images found
    returnMethode.FileFinderReturn(this.getFilesInArray());
  }

  /**
   * converts the vector of files into an array
   * @return File[]
   */
  public File[] getFilesInArray() {
    if (this.FilesFound.size() == 0)
      return null;
    File[] filesFoundArray = new File[this.FilesFound.size()];
    int i = 0;
    for (Enumeration e = this.FilesFound.elements(); e.hasMoreElements(); ) {
      filesFoundArray[i++] = (File) e.nextElement();
    }
    return filesFoundArray;
  }

  /**
   * recusive finds images in the folder passed in
   * @param path File
   */
  public void findfiles(File path) {

    //get all the images or folders in this folder
    File[] files = path.listFiles(
        new FileFilter() {
      public boolean accept(File d) {
        return (d.getName().endsWith(".jpg") ||
                d.getName().endsWith(".jpeg") ||
                d.getName().endsWith(".JPG") ||
                d.getName().endsWith(".GIF") ||
                d.getName().endsWith(".gif") ||
                (d.isDirectory() && !d.isHidden()));
      }
    }
    );

    //if there are files or folders in this folder
    if(files != null){

      //run through all of the files of folders
      for (int i = 0; i < files.length; i++) {

        //if the file is a directory
        if (files[i].isDirectory()){

          //check this folder for images
          findfiles(files[i]);

        }
        else {

          //add the image file to the vector of images files
          FilesFound.add(files[i]);

          //display the amount of images found
          amountFoundLabel.setText(FilesFound.size() + "");

        }
      }
    }
  }
}
