package com.base.datarecovery.help

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import com.base.datarecovery.bean.MediaBean


object MediaStoreHelp {


    @SuppressLint("Recycle")
    fun Context.getAllMedia(filter: (size: Long) -> Boolean): MutableList<MediaBean> {
        val files: MutableList<MediaBean> = ArrayList()
        var cursor: Cursor? = null
        try {
            val uri = MediaStore.Files.getContentUri("external")
            cursor = contentResolver.query(uri, null, null, null, null)

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val path = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA).let { cursor.getString(it) } ?: ""
                    val mimeType =
                        cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE).let { cursor.getString(it) } ?: ""
                    val size = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE).let { cursor.getLong(it) }
                    val modifiedDate =
                        cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED).let { cursor.getLong(it) }
                    val info = MediaBean(
                        path = path,
                        size = size,
                        mimeType = mimeType,
                        time = modifiedDate
                    )
                    if (filter(size)) {
                        files.add(info)
                    }
                }
            }

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
        return files
    }

    @SuppressLint("Range")
    fun Context.getImageMedia(
        list: ArrayList<MediaBean>,
    ): ArrayList<MediaBean> {

        val projection = arrayOf(
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.MIME_TYPE,
            MediaStore.Images.Media.DATE_MODIFIED,
        )

        var cursor: Cursor? = null
        val externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI // 你也可以使用INTERNAL_CONTENT_URI来查询内部存储
        try {
            cursor = contentResolver.query(
                externalUri,
                projection,
                null,
                null,
                MediaStore.Images.Media.DATE_TAKEN + " DESC"// 排序方式，按照拍摄
            )

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val path =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))

                    val uri =
                        ContentUris.withAppendedId(
                            externalUri,
                            cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID))
                        )
                    val time = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED))
                    val mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE))

                    list.add(MediaBean(path = path, uri = uri, time = time, mimeType = mimeType))
                }
            }
        } catch (e: Exception) {

        } finally {
            cursor?.close()
        }

        return list
    }


    @SuppressLint("Range")
    fun Context.getVideoMedia(list: ArrayList<MediaBean>): ArrayList<MediaBean> {

//        MediaStore.Video.Media.DATE_TAKEN：表示视频拍摄的时间，
//        MediaStore.Video.Media.DATE_ADDED：表示视频文件被添加到MediaStore数据库的时间
//        MediaStore.Video.Media.DATE_MODIFIED：表示视频文件最后被修改的时间，

        val projection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.DATE_MODIFIED,
            MediaStore.Video.Media.MIME_TYPE,
//            MediaStore.Video.Media.DATE_TAKEN,
        )
        val externalUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(
                externalUri,
                projection,
                null,  // 选择条件，null表示查询所有
                null,  // 选择参数，配合选择条件使用
                MediaStore.Video.Media.DATE_TAKEN + " DESC" // 按日期降序排序
            )

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 获取视频文件的属性
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA))

                    val uri =
                        ContentUris.withAppendedId(
                            externalUri,
                            cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID))
                        )
                    val time = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED))
                    val mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE))

                    list.add(MediaBean(path = path, uri = uri, time = time, mimeType = mimeType))
                }

            }
        } catch (e: Exception) {

        } finally {
            cursor?.close()
        }
        return list
    }


    val commonMediaDir = arrayOf(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).absolutePath,
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath,
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath,
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).absolutePath,
    )

    fun Context.updateMediaStore(
        filePath: Array<String> = commonMediaDir
    ) {
        MediaScannerConnection.scanFile(
            this, filePath, null
        ) { path: String?, uri: Uri? -> }
    }
}