package com.swiftcleaner.chovey.model.tool;

import android.os.Environment;

import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import com.swiftcleaner.chovey.model.bean.MeCleanBean;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class FileHelps {
    private static final String WHATS_APP_MEDIA_DIR = "Android/media/com.whatsapp/WhatsApp/Media/";

    public static List<CleanFileBean> findWhatsappFiles() {
        File rootDir = new File(getAppSpecificDirPath(WHATS_APP_MEDIA_DIR));
        return findFilesRecursive(rootDir, new String[]{});
    }
    //查找外部存储中的空文件夹
    public static List<CleanFileBean> findEmptyFolders() {
        File externalStorageDir = Environment.getExternalStorageDirectory();
        String[] filters = new String[]{"/storage/emulated/0/Android/data", "/storage/emulated/0/Android/obb"};
        List<File> emptyFolders = getAllEmptyFolders(externalStorageDir, filters);
        return emptyFolders.stream()
                .map(folder -> new CleanFileBean(folder.getName(), folder.getPath(), 4 * 1024))
                .collect(Collectors.toList());
    }
    //查找外部存储目录下以.temp 为后缀的文件。
    public static List<CleanFileBean> findTempFiles() {
        File rootDir = Environment.getExternalStorageDirectory();
        return findFilesRecursive(rootDir, new String[]{".temp"});
    }
    //查找外部存储目录下以.apk 和.aab 为后缀的文件。
    public static List<CleanFileBean> findApkFiles() {
        File rootDir = Environment.getExternalStorageDirectory();
        return findFilesRecursive(rootDir, new String[]{".apk", ".aab"});
    }
    //查找外部存储目录下以.log 为后缀的文件。
    public static List<CleanFileBean> findLogFiles() {
        File rootDir = Environment.getExternalStorageDirectory();
        return findFilesRecursive(rootDir, new String[]{".log"});
    }

    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        deleteIfExists(file);
    }

    private static boolean deleteIfExists(File file) {
        if (file != null && file.exists()) {
            return file.delete();
        }
        return false;
    }

    private static List<CleanFileBean> findFilesRecursive(File dir, String[] suffixes) {
        try {
            return Files.walk(dir.toPath())
                    .filter(Files::isRegularFile)
                    .filter(path -> Arrays.stream(suffixes).anyMatch(suffix -> path.getFileName().toString().endsWith(suffix)))
                    .map(path -> {
                        File file = path.toFile();
                        return new CleanFileBean(file.getName(), file.getPath(), file.length());
                    })
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    private boolean endsWith(File file, String[] suffixes) {
        if (suffixes.length == 0) {
            return true;
        }
        String fileName = file.getName().toLowerCase();
        for (String suffix : suffixes) {
            if (fileName.endsWith(suffix.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    private static String getAppSpecificDirPath(String relativePath) {
        return Environment.getExternalStorageDirectory() + "/" + relativePath;
    }

    private static List<File> getAllEmptyFolders(File root, String[] filters) {
        File[] files = root.listFiles();
        if (files == null) {
            return Collections.emptyList();
        }
        return Stream.of(files)
                .flatMap(file -> getAllEmptyFolders(file, filters).stream())
                .filter(folder -> folder.isDirectory() &&!contains(filters, folder.getPath()) &&!folder.isHidden() && folder.list()!= null && folder.list().length == 0)
                .collect(Collectors.toList());
    }
    private static boolean contains(String[] filters, String path) {
        for (String filter : filters) {
            if (filter.equals(path)) {
                return true;
            }
        }
        return false;
    }


}
