package com.base.datarecovery.utils

import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import android.provider.MediaStore
import com.base.datarecovery.bean.FileBean


object LargeFileUtils {
    val fileList = mutableListOf<FileBean>()
    @SuppressLint("Range")
    fun getFilesByType(context: Context, onEnd: (() -> Unit)? = null): List<FileBean> {
        fileList.clear()
        var c: Cursor? = null
        try {
            val mContentResolver = context.contentResolver
            c = mContentResolver.query(
                MediaStore.Files.getContentUri("external"),
                null,
                null,
                null,
                null
            )
            if(c!=null){
                while (c.moveToNext()) {
                    val displayName =
                        c.getString(c.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME))
                    val size = c.getLong(c.getColumnIndex(MediaStore.MediaColumns.SIZE))
                    val mimeType =
                        c.getString(c.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE))
                    val dateModified =
                        c.getLong(c.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED))
                    val filePath =
                        c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA))

                    fileList.add(
                        FileBean(
                            displayName,
                            filePath,
                            size,
                            false,
                            getFileExtension(displayName),
                            dateModified,
                            false
                        )
                    )
                }
                // fileList.sortByDescending { it.time }
            }

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            c?.close()
            onEnd?.invoke()
        }
        return fileList
    }
    fun getFileExtension(fileName: String): String {
        var extension = ""
        val i = fileName.lastIndexOf('.')
        if (i > 0 && i < fileName.length - 1) {
            extension = fileName.substring(i + 1)
        }
        return extension
    }
}