package com.base.filerecoveryrecyclebin.activity.recyclebin

import android.annotation.SuppressLint
import android.content.Context
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import android.os.Handler
import android.provider.MediaStore
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.gson.Gson
import java.io.File


class MediaContentObserver(val context: Context, val handler: Handler? = null) : ContentObserver(null) {

    private val TAG = "MediaContentObserver"


    override fun onChange(selfChange: Boolean, uri: Uri?) {
        super.onChange(selfChange, uri)
        uri?.let { queryNewMediaFiles(it) }
    }

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

        val cursor: Cursor? = context.contentResolver.query(uri, projection, null, null, null)
        if (cursor != null) {
            try {
                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))
                    // 处理新文件路径
                    backupRecycleBinFile(name, path, mimeType)
                }
            } catch (e: Exception) {

            } finally {
                cursor.close()
            }

        }
    }

    private fun backupRecycleBinFile(name: String, path: String, mimeType: String) {
        LogEx.logDebug(TAG, "name=$name path=$path mimeType=$mimeType")

        val file = context.filesDir
        val recycleBinDir = File(file, "RecycleBin")
        if (!recycleBinDir.exists()) {
            recycleBinDir.mkdirs()
        }

        val src = File(path)
        val recycleBinFile = File(recycleBinDir, ".$name")
        if (!recycleBinFile.exists()) {
            src.copyTo(recycleBinFile, true)
            val binBean = RecycleBinBean(src.path, 0, src.length(), mimeType)
            val binFile = File(recycleBinDir, ".$name.bin")
            binFile.createNewFile()
            binFile.writeText(Gson().toJson(binBean))
            LogEx.logDebug(TAG, "回收站备份成功")
            handler?.sendEmptyMessage(99)
        }

    }
}
