package com.swiftcleaner.chovey.model.tool;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;
import androidx.collection.ArrayMap;

import com.swiftcleaner.chovey.model.bean.CleanFileBean;
import android.util.Pair;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MediaHelps {
    private static final String[] PROJECTION = {
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns.DATE_MODIFIED,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns._ID
    };

    private static final String EXTERNAL = "external";


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static void updateMedia(Context context, String[] paths) {
        if (paths != null && paths.length > 0) {
            MediaScannerConnection.scanFile(context, paths, null, null);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static List<CleanFileBean> findFiles(Context context, long size) {
        return queryFilesWithSize(context, MediaStore.Files.getContentUri(EXTERNAL), size);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static List<CleanFileBean> findSpecifiedFiles(Context context) {
        String[] suffixes = { "%.log", "%.apk", "%.aab", "%.temp", "%.LOG", "%.APK", "%.AAB", "%.TEMP" };
        return queryFilesWithSuffixes(context, MediaStore.Files.getContentUri(EXTERNAL), suffixes);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static Map<String, List<CleanFileBean>> findScreenshotsFiles(Context context) {
        String selection = MediaStore.Images.Media.RELATIVE_PATH + " LIKE ?";
        String[] selectionArgs = { "%Screenshots%" };
        List<CleanFileBean> list = query(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PROJECTION, selection, selectionArgs);
        Map<String, List<CleanFileBean>> map = new ArrayMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM", Locale.getDefault());
        for (CleanFileBean file : list) {
            String dateKey = dateFormat.format(new Date(file.getLastModified()));
            map.putIfAbsent(dateKey, new ArrayList<>());
            map.get(dateKey).add(file);
        }
        return map;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static List<CleanFileBean> findImageFiles(Context context, long size) {
        return queryFilesWithSize(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, size);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static List<CleanFileBean> findVideoFiles(Context context, long size) {
        return queryFilesWithSize(context, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, size);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static List<CleanFileBean> findAudioFiles(Context context, long size) {
        return queryFilesWithSize(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, size);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static List<CleanFileBean> findDocFiles(Context context, long size) {
        String[] mimeTypes = {
                "text/plain",
                "application/msword",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/vnd.ms-excel",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "application/pdf",
        };
        return queryFilesWithMimeTypes(context, MediaStore.Files.getContentUri(EXTERNAL), mimeTypes, size);
    }
    //文件类型（如图片、视频等）来查找文件
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private static List<CleanFileBean> queryFilesWithSuffixes(Context context, Uri uri, String[] suffixes) {
        String[] selectionArgs = new String[suffixes.length];
        for (int i = 0; i < suffixes.length; i++) {
            selectionArgs[i] = suffixes[i];
        }
        String selection = TextUtils.join(" OR ", Collections.nCopies(suffixes.length, "LOWER(" + MediaStore.Files.FileColumns.DISPLAY_NAME + ") LIKE ?"));
        return query(context, uri, PROJECTION, selection, selectionArgs);
    }
    //该方法用于查找大小大于或等于指定值的文件，适用于清理大文件或者查找特定大小范围的文件。
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private static List<CleanFileBean> queryFilesWithSize(Context context, Uri uri, long size) {
        String selection = null;
        String[] selectionArgs = null;
        if (size > 0) {
            selection = MediaStore.Files.FileColumns.SIZE + " >= ?";
            selectionArgs = new String[]{String.valueOf(size)};
        }
        return query(context, uri, PROJECTION, selection, selectionArgs);
    }
    //该方法通过文件的 MIME 类型和大小来筛选文件，适用于需要根据文件类型和大小来进行更精细查询的场景。
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private static List<CleanFileBean> queryFilesWithMimeTypes(Context context, Uri uri, String[] mimeTypes, long size) {
        Pair<String, String[]> selection = buildSelectionWithMimeTypes(mimeTypes, size);
        return query(context, uri, PROJECTION, selection.first, selection.second);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private static Pair<String, String[]> buildSelectionWithMimeTypes(String[] mimeTypes, long size) {
        String mimeTypeConditions = TextUtils.join(" OR ", Arrays.asList(mimeTypes)).replace("?", "${MediaStore.Files.FileColumns.MIME_TYPE}=?");
        String sizeCondition = MediaStore.Files.FileColumns.SIZE + " >= ?";
        String selection = "(" + mimeTypeConditions + ") AND (" + sizeCondition + ")";
        String[] selectionArgs = Arrays.copyOf(mimeTypes, mimeTypes.length + 1);
        selectionArgs[mimeTypes.length] = String.valueOf(size);
        return new Pair<>(selection, selectionArgs);
    }

    public static List<CleanFileBean> query(
            Context context,
            Uri uri,
            String[] projection,
            String selection,
            String[] selectionArgs) {

        List<CleanFileBean> list = new ArrayList<>();
        Cursor cursor = null;

        try {
            String sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC";
            cursor = context.getContentResolver().query(
                    uri,
                    projection,
                    selection,
                    selectionArgs,
                    sortOrder
            );

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
                    @SuppressLint("Range") String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
                    @SuppressLint("Range") long size = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns.SIZE));
                    @SuppressLint("Range") long dateModified = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED)) * 1000;
                    @SuppressLint("Range") String mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE));
                    // 加载缩略图
                    @SuppressLint("Range") Bitmap icon = MediaStore.Images.Thumbnails.getThumbnail(
                            context.getContentResolver(),
                            cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID)),
                            MediaStore.Images.Thumbnails.MINI_KIND,
                            null
                    );

                    CleanFileBean fileBean = new CleanFileBean(displayName, filePath, icon, size, dateModified, mimeType);
                    fileBean.setIcon1(icon); // 设置缩略图
                    fileBean.setLength(size);
                    list.add(fileBean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return list;
    }
}
