package com.tt.honeyDue.storage

import java.util.prefs.Preferences

/**
 * JVM implementation of TaskCacheManager using Java Preferences.
 * Note: JVM/Desktop doesn't have widgets, so dirty flag methods are no-ops.
 */
actual class TaskCacheManager {
    private val prefs = Preferences.userRoot().node(NODE_NAME)

    actual fun saveTasks(tasksJson: String) {
        prefs.put(KEY_TASKS, tasksJson)
        prefs.flush()
    }

    actual fun getTasks(): String? {
        return prefs.get(KEY_TASKS, null)
    }

    actual fun clearTasks() {
        prefs.remove(KEY_TASKS)
        prefs.flush()
    }

    /**
     * Check if tasks need refresh. JVM doesn't have widgets, always returns false.
     */
    actual fun areTasksDirty(): Boolean {
        return prefs.getBoolean(KEY_DIRTY_FLAG, false)
    }

    /**
     * Mark tasks as dirty. JVM doesn't have widgets but supports the interface.
     */
    actual fun markTasksDirty() {
        prefs.putBoolean(KEY_DIRTY_FLAG, true)
        prefs.flush()
    }

    /**
     * Clear the dirty flag.
     */
    actual fun clearDirtyFlag() {
        prefs.putBoolean(KEY_DIRTY_FLAG, false)
        prefs.flush()
    }

    companion object {
        private const val NODE_NAME = "com.honeydue.cache"
        private const val KEY_TASKS = "cached_tasks"
        private const val KEY_DIRTY_FLAG = "tasks_dirty"

        @Volatile
        private var instance: TaskCacheManager? = null

        fun getInstance(): TaskCacheManager {
            return instance ?: synchronized(this) {
                instance ?: TaskCacheManager().also { instance = it }
            }
        }
    }
}
