package com.base.filerecoveryrecyclebin.activity.recyclebin

import android.annotation.SuppressLint
import android.os.FileObserver
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

@SuppressLint("NewApi")
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) = Thread {


        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")
            }
        }

    }.start()

}