package com.base.filerecoveryrecyclebin.activity.recyclebin

import android.annotation.SuppressLint
import android.os.Build
import android.os.FileObserver
import android.os.Handler
import androidx.annotation.RequiresApi
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinFileEx.findRecycleBinFile
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinFileEx.findRecycleBinJsonFile
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.gson.Gson
import java.io.File

@RequiresApi(Build.VERSION_CODES.Q)
class MyFileObserver(files: List<File>) : FileObserver(files, ALL_EVENTS) {

    private val TAG = "MyFileObserver"

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

                }

                OPEN -> {}
                MOVED_FROM -> {
                    LogEx.logDebug(TAG, "MOVED_FROM path=$path")
                    recordRecycleBinFile(path)
                }

                MOVED_TO -> {

                }

                CREATE -> {

                }

                DELETE -> {
                    LogEx.logDebug(TAG, "DELETE path=$path")
                    recordRecycleBinFile(path)
                }

                DELETE_SELF -> {
                    LogEx.logDebug(TAG, "DELETE_SELF path=$path")
                    recordRecycleBinFile(path)
                }
            }

        }


    }

    private fun recordRecycleBinFile(namePath: String) {


        val recycleBinFile = findRecycleBinFile(namePath)
        val recycleBinJsonFile = findRecycleBinJsonFile(namePath)

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

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

                val wJson = Gson().toJson(bean)
                recycleBinJsonFile.writeText(wJson)
                LogEx.logDebug(TAG, "writeText wJson=$wJson")
            }
        }

    }

}