package com.base.pdfviewerscannerwhite.service

import android.annotation.SuppressLint
import android.content.Context
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.fcm.NotificationUiUtil
import com.base.pdfviewerscannerwhite.fcm.PopupConstObject
import com.base.pdfviewerscannerwhite.utils.LogEx

/**
 * Observer MediaContent add
 */
class MediaContentObserver(val context: Context) : ContentObserver(null) {

    private val TAG = "MediaContentObserver"


    override fun onChange(selfChange: Boolean, uri: Uri?) {
        super.onChange(selfChange, uri)
        LogEx.logDebug(TAG, "uri=${uri.toString()}")
        if (uri.toString().contains("images")) {
            NotificationUiUtil.sendNotificationIfCan(
                context,
                ConstObject.NOTIFICATION_ACTION_NEW_IMAGE_PDF,
                PopupConstObject.POPUP_WHERE_MEDIA_CHANGE
            )
        }
//        uri?.let { queryNewMediaFiles(it) }
    }


    @SuppressLint("Range")
    private fun queryNewMediaFiles(uri: Uri) = Thread {
        // 查询新添加的媒体文件
        val projection = arrayOf(
            MediaStore.MediaColumns.DISPLAY_NAME,
            MediaStore.MediaColumns.DATA,
            MediaStore.MediaColumns.MIME_TYPE,
            MediaStore.MediaColumns.SIZE,
        )

        val cursor: Cursor? = context.contentResolver.query(uri, projection, null, null, null)
        if (cursor != null) {
            LogEx.logDebug(TAG, "cursor=$cursor")
            try {
                if (cursor.count > 0) {
                    while (cursor.moveToNext()) {
                        val name = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME))
                        val path = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA))
                        val mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE))
                        val size = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.SIZE))
                        LogEx.logDebug(TAG, "path=$path")
                        // 处理新文件路径

                    }
                } else {
                    LogEx.logDebug(TAG, "count=0 deleted file uri")
                }

            } catch (e: Exception) {
                e.printStackTrace()
                LogEx.logDebug(TAG, "Exception=$e")
            } finally {
                cursor.close()
            }

        } else {
            LogEx.logDebug(TAG, "cursor=$cursor")
        }
    }.start()

}
