package com.nbsp.materialfilepicker.utils;

import android.support.annotation.Nullable;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Dimorinny on 24.10.15.
 */
public class FileUtils {
    public static List<File> getFileListByDirPath(String path,
                                                  @Nullable Pattern fileFilter,
                                                  boolean directoriesFilter,
                                                  boolean showHidden) {
        File directory = new File(path);
        List<File> resultFiles = new ArrayList<>();

        File[] files = directory.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isHidden()) {
                    if (showHidden) {
                        resultFiles.add(f);
                    }
                    continue;
                }

                if (f.isDirectory() && !directoriesFilter) {
                    resultFiles.add(f);
                    continue;
                }

                if (fileFilter != null && fileFilter.matcher(f.getName()).matches()) {
                    resultFiles.add(f);
                }
            }

            Collections.sort(resultFiles, new FileComparator());
        }

        return resultFiles;
    }

    public static String cutLastSegmentOfPath(String path) {
        return path.substring(0, path.lastIndexOf("/"));
    }

    public static String getReadableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}

@@ -831,24 +831,25 @@
  : files) %7B%0A
+%0A
             
@@ -864,44 +864,103 @@
 f.is
-Hidden()) %7B%0A                    if (
+Directory() && !directoriesFilter) %7B%0A                    if (!f.isHidden() %7C%7C (f.isHidden() && 
 show
@@ -958,32 +958,33 @@
 ) && showHidden)
+)
  %7B%0A             
@@ -1110,137 +1110,179 @@
 f (f
-.isDirectory() && !directoriesFilter) %7B%0A                    resultFiles.add(f);%0A                    continue;%0A         
+ileFilter != null) %7B%0A                    if (fileFilter.matcher(f.getName()).matches())%0A                        if (!f.isHidden() %7C%7C (f.isHidden() && showHidden)) %7B%0A
       
- %7D%0A%0A
     
@@ -1297,76 +1297,82 @@
     
-if (fileFilter != null && fileFilter.matcher(f.getName()).matches())
+      resultFiles.add(f);%0A                        %7D%0A                %7D else
  %7B%0A 
@@ -1420,32 +1420,33 @@
               %7D%0A
+%0A
             %7D%0A%0A 

Fix filters. Fixes #11 and #19