package com.base.filerecoveryrecyclebin.activity.recyclebin

import android.os.Build
import android.os.FileObserver
import android.os.Handler
import androidx.annotation.RequiresApi
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.lang.reflect.Type

@RequiresApi(Build.VERSION_CODES.Q)
class MyFileObserver(val handler: Handler? = null, files: List<File>) : FileObserver(files, ALL_EVENTS) {

    private val TAG = "MyFileObserver"

    override fun onEvent(event: Int, path: String?) {
        if (path != null) {
//            LogEx.logDebug(TAG, "onEvent=$event path=$path")
            val filteredEvent = event and ALL_EVENTS
            LogEx.logDebug(TAG, "filteredEvent=$filteredEvent path=$path")
            when (filteredEvent) {
                CLOSE_NOWRITE -> {

                }

                OPEN -> {}
                MOVED_FROM -> {
                    recordRecycleBinFile(path)
                }

                MOVED_TO -> {

                }

                CREATE -> {

                }

                DELETE -> {
                    recordRecycleBinFile(path)
                }

                DELETE_SELF -> {
                    recordRecycleBinFile(path)
                }
            }

        }


    }

    private fun recordRecycleBinFile(path: String) {
        val file = BaseApplication.context.filesDir
        val recycleBinDir = File(file, "RecycleBin")
        if (!recycleBinDir.exists()) {
            recycleBinDir.mkdirs()
        }

        val recycleFile = recycleBinDir.listFiles()?.find { it.name.contains(path) }
        val recycleBinFile = recycleBinDir.listFiles()?.find { it.name.contains(".$path.bin") }

        LogEx.logDebug(TAG, "recycleFile=$recycleFile")
        LogEx.logDebug(TAG, "recycleBinFile=$recycleBinFile")

        if (recycleFile != null && recycleBinFile != null) {
            runCatching {
                val rJson = recycleBinFile.readText()
                val bean = Gson().fromJson(rJson, RecycleBinBean::class.java)
                bean.deleted = true
                bean.deleteTime = System.currentTimeMillis()

                val wJson = Gson().toJson(bean)
                recycleBinFile.writeText(wJson)
                handler?.sendEmptyMessage(100)
            }
        }

    }

}