package com.all.pdfreader.pro.app.util

import android.content.Context
import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import androidx.lifecycle.LifecycleObserver
import com.all.pdfreader.pro.app.room.repository.PdfRepository
import com.all.pdfreader.pro.app.util.FileUtils.getFileFromUri
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class FileChangeObserver(
    private val context: Context,
) : LifecycleObserver {

    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var contentObserver: ContentObserver? = null
    private var isObserving = false

    // 防抖机制，避免频繁触发
    private var lastScanTime = 0L
    private val debounceDelay = 3000L // 3秒防抖

    fun startObserving() {
        if (isObserving) return

        contentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
            override fun onChange(selfChange: Boolean, uri: Uri?) {
                super.onChange(selfChange, uri)
                if (uri != null) {
                    val file = getFileFromUri(context, uri)
                    if (file != null) {
                        Log.d("ocean", "修改的文件: ${file.absolutePath}")
                        // 可以传给你的增量扫描逻辑

                        handleFileChange(file)
                    }
                }
            }
        }

        try {
            context.contentResolver.registerContentObserver(
                MediaStore.Files.getContentUri("external"),
                true,
                contentObserver!!
            )
            isObserving = true
            Log.d("ocean", "📡 开始监听文件变化")
        } catch (e: Exception) {
            Log.e("ocean", "❌ 注册文件变化监听器失败", e)
        }
    }

    fun stopObserving() {
        if (!isObserving) return

        try {
            contentObserver?.let { observer ->
                context.contentResolver.unregisterContentObserver(observer)
            }
            isObserving = false
            Log.d("ocean", "📡 停止监听文件变化")
        } catch (e: Exception) {
            Log.e("ocean", "❌ 注销文件变化监听器失败", e)
        }
    }

    private fun handleFileChange(file: File) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastScanTime < debounceDelay) {
            return // 防抖
        }

        lastScanTime = currentTime

        scope.launch {
            delay(debounceDelay) // 额外延迟，避免频繁扫描

            if (StoragePermissionHelper.hasBasicStoragePermission(context)) {
                Log.d("ocean", "📂 检测到文件变化，可以执行增量扫描...")
                val pdfRepository = PdfRepository.getInstance()
                val existingDoc = pdfRepository.getDocumentByPath(file.absolutePath)
                if (existingDoc != null) {
                    LogUtil.logDebug(
                        "ocean",
                        "PdfScanner:    📖 ${existingDoc.fileName} - ${existingDoc.pageCount}页 - ${
                            FileUtils.formatFileSize(
                                existingDoc.fileSize
                            )
                        } - ${existingDoc.thumbnailPath}"
                    )
                }
            }
        }
    }
}