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.provider.MediaStore
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinFileEx.getRecycleBinDir
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.gson.Gson
import java.io.File

/**
 * 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")) {

        }
        if (uri.toString().contains("video")) {

        }
        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")
                        // 处理新文件路径
                        backupRecycleBinFile(name, path, uri, mimeType)
                    }
                } 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()

    private fun backupRecycleBinFile(name: String, path: String, uri: Uri, mimeType: String) {
        val src = File(path)

        LogEx.logDebug(TAG, "name=$name path=$path mimeType=$mimeType size=${src.length()}")

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

        LogEx.logDebug(TAG, "size=${src.length()}")
        if (src.length() > 0L) {
            val recycleBinFile = File(getRecycleBinDir(), ".$name")
            src.copyTo(recycleBinFile, true)
//            val binBean = RecycleBinBean(src.path, uri, deleteTime = 0, size = src.length(), mimeType = mimeType)
//            val binFile = File(recycleBinDir, ".$name.bin")
//            binFile.createNewFile()
//            binFile.writeText(Gson().toJson(binBean))
//            LogEx.logDebug(TAG, "RecycleBin backup")
        }
    }
}
