package com.secspace.lib.common.utils;

import android.support.annotation.IntDef;
import android.util.Log;

import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;

public class FileTraverseUtil {
    private static final String TAG = "FileTraverseUtil";

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({Filter.ALL, Filter.IMAGE, Filter.VIDEO, Filter.AUDIO, Filter.DOC, Filter.GIF})
    public @interface Filter {
        int ALL = -1;
        int IMAGE = 0;
        int VIDEO = 1;
        int AUDIO = 2;
        int DOC = 3;
        int GIF = 4;
    }

    private static List<File> mFiles = new ArrayList<>();

    /**
     * @param dirPath     文件夹路径
     * @param includeHide 是否包含隐藏文件夹和隐藏文件
     * @param filter      过滤模式
     * @return
     */
    public static List<File> getFileList(String dirPath, boolean includeHide, int filter) {
        File dir = new File(dirPath);
        if (!dir.isDirectory()) {
            return null;
        }
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return null;
        }
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String path = file.getAbsolutePath();
            Log.d(TAG, "file: " + file);
            Log.d(TAG, "path: " + path);
            if (file.isDirectory()) {
                if (!includeHide && file.getName().startsWith(".")) {
                    Log.d(TAG, "It's a hidden folder.");
                    continue;
                }
                getFileList(path, includeHide, filter);
            } else {
                if (!includeHide && file.getName().startsWith(".")) {
                    Log.d(TAG, "It's a hidden file.");
                    continue;
                }
                switch (filter) {
                    case Filter.IMAGE:
                        if (FileTypeUtil.isImageFile(path))
                            mFiles.add(file);
                        break;
                    case Filter.DOC:
                        if (FileTypeUtil.isDocFile(path))
                            mFiles.add(file);
                        break;
                    case Filter.VIDEO:
                        if (FileTypeUtil.isVideoFile(path))
                            mFiles.add(file);
                        break;
                    case Filter.AUDIO:
                        if (FileTypeUtil.isAudioFile(path))
                            mFiles.add(file);
                        break;
                    case Filter.GIF:
                        if (FileTypeUtil.isGifFile(path))
                            mFiles.add(file);
                        break;
                    case Filter.ALL:
                    default:
                        mFiles.add(file);
                        break;
                }
            }
        }
        return mFiles;
    }
}
