package com.swiftcleaner.chovey.model.tool;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.ContextCompat;

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.ArrayList;
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> findWhatsappFiles() {
        File rootDir = new File(getAppSpecificDirPath(WHATS_APP_MEDIA_DIR));
        if (!rootDir.exists() || !rootDir.isDirectory()) {
            Log.e("FilePath", "Directory does not exist or is not a directory: " + rootDir.getAbsolutePath());
            return new ArrayList<>();
        }
        // Check for read storage permission

        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);

        List<CleanFileBean> fileBeans = new ArrayList<>();
        for (File folder : emptyFolders) {
            fileBeans.add(new CleanFileBean(folder.getName(), folder.getPath(), 4 * 1024));
        }
        return fileBeans;
    }


    //查找外部存储目录下以.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()) {
            Log.d("selectedFiles","exists");
            return file.delete();
        }
        return false;
    }

    private static List<CleanFileBean> findFilesRecursive(File dir, String[] suffixes) {
        List<CleanFileBean> fileBeans = new ArrayList<>();
        try {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        fileBeans.addAll(findFilesRecursive(file, suffixes));
                    } else if (file.isFile() && endsWith(file.getName(), suffixes)) {
                        fileBeans.add(new CleanFileBean(file.getName(), file.getPath(), file.length()));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBeans;
    }

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

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

    private static List<File> getAllEmptyFolders(File root, String[] filters) {
        List<File> emptyFolders = new ArrayList<>();

        File[] files = root.listFiles();
        if (files == null) {
            return emptyFolders;
        }

        boolean isEmpty = true;
        for (File file : files) {
            if (file.isDirectory()) {
                emptyFolders.addAll(getAllEmptyFolders(file, filters));
                isEmpty = false; // 如果子文件夹不为空，当前文件夹也不为空
            } else {
                isEmpty = false; // 如果文件夹中有文件，标记为非空
            }
        }

        if (isEmpty && isTargetEmptyFolder(root, filters)) {
            emptyFolders.add(root);
        }

        return emptyFolders;
    }

    private static boolean isTargetEmptyFolder(File folder, String[] filters) {
        if (!folder.isDirectory()) {
            return false;
        }
        if (contains(filters, folder.getPath())) {
            return false;
        }
        if (folder.isHidden()) {
            return false;
        }
        String[] files = folder.list();
        return files == null || files.length == 0;
    }

    private static boolean contains(String[] filters, String path) {
        for (String filter : filters) {
            if (filter.equals(path)) {
                return true;
            }
        }
        return false;
    }
}