package ru.job4j.io;

import java.io.File;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * Class to search files with specified extensions.
 *
 * @author Tolstonogov Alexey
 * @version 3.0
 */
public class Search {
    /**
     *Searches files with specified extensions in specified directory.
     *
     * @param parent directory in which the files are searched
     * @param exts extensions with which files are searched
     * @return list with found files
     */
    public List<File> files(String parent, List<String> exts) {
        List<File> result = new LinkedList<>();
        File pFile = new File(parent);
        Deque<File> dirFiles = new LinkedList<>();
        dirFiles.offer(pFile);
        File file;
        while (!dirFiles.isEmpty()) {
            file = dirFiles.poll();
            if (file.isDirectory()) {
                for (File f: file.listFiles()) {
                    dirFiles.offer(f);
                }
            } else {
                if (checkExt(file, exts)) {
                    result.add(file);
                }
            }
        }
        result.sort(new Comparator<>() {
            @Override
            public int compare(File o1, File o2) {
                return o1.getAbsolutePath().compareTo(o2.getAbsolutePath());
            }
        });
        return result;
    }

    /**
     * Checks whether extension of file is included in list of extensions.
     *
     * @param file checked file
     * @param exts list of extensions
     * @return true if included, false - if excluded
     */
    private boolean checkExt(File file, List<String> exts) {
        boolean result = false;
        for (String ext : exts) {
            if (file.getName().endsWith(String.format(".%s", ext))) {
                result = true;
                break;
            }
        }
        return result;
    }
}
