package com.base.superfilemanager.helps.file

import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore

object MediaStoreEx {
    fun recentImage(context: Context): ArrayList<Uri> {
        val list = arrayListOf<Uri>()
        var cursor: Cursor? = null
        // 查询照片的Uri和字段
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME)
        //DESC 降列
        //ASC 升序
        val sortOrder = MediaStore.Images.ImageColumns._ID + " DESC"
        try {
            // 执行查询
            cursor = context.contentResolver.query(uri, projection, null, null, sortOrder)

            // 遍历结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    val id =
                        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
                    list.add(ContentUris.withAppendedId(uri, id))
                    if (list.size == 10) {
                        break
                    }
                } while (cursor.moveToNext())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
        return list
    }

    fun recentVideo(context: Context): ArrayList<Uri> {
        val list = arrayListOf<Uri>()
        var cursor: Cursor? = null
        // 查询照片的Uri和字段
        val uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME)
        //DESC 降列
        //ASC 升序
        val sortOrder = MediaStore.Video.VideoColumns._ID + " DESC"
        try {
            // 执行查询
            cursor = context.contentResolver.query(uri, projection, null, null, sortOrder)

            // 遍历结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    val id =
                        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))
                    list.add(ContentUris.withAppendedId(uri, id))
                    if (list.size == 10) {
                        break
                    }
                } while (cursor.moveToNext())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
        return list
    }

}

