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

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import java.util.concurrent.TimeUnit

object ScanManager {
    
    private const val PREF_NAME = "scan_preferences"
    private const val KEY_FIRST_SCAN_DONE = "first_scan_done"
    private const val KEY_LAST_SCAN_TIME = "last_scan_time"
    private const val SCAN_INTERVAL_HOURS = 24L
    
    fun shouldScan(context: Context): Boolean {
        val prefs = getSharedPreferences(context)
        val currentTime = System.currentTimeMillis()
        
        // 首次启动需要扫描
        if (!prefs.getBoolean(KEY_FIRST_SCAN_DONE, false)) {
            return true
        }
        
        // 检查24小时间隔
        val lastScanTime = prefs.getLong(KEY_LAST_SCAN_TIME, 0)
        val hoursSinceLastScan = TimeUnit.MILLISECONDS.toHours(currentTime - lastScanTime)
        
        return hoursSinceLastScan >= SCAN_INTERVAL_HOURS
    }
    
    fun markScanComplete(context: Context) {
        getSharedPreferences(context).edit {
            putBoolean(KEY_FIRST_SCAN_DONE, true)
            putLong(KEY_LAST_SCAN_TIME, System.currentTimeMillis())
        }
    }
    
    fun getLastScanTime(context: Context): Long {
        return getSharedPreferences(context).getLong(KEY_LAST_SCAN_TIME, 0)
    }
    
    fun resetScanState(context: Context) {
        getSharedPreferences(context).edit {
            putBoolean(KEY_FIRST_SCAN_DONE, false)
            putLong(KEY_LAST_SCAN_TIME, 0)
        }
    }
    
    private fun getSharedPreferences(context: Context): SharedPreferences {
        return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    }
}