package com.tt.honeyDue.storage

import android.content.Context
import android.content.SharedPreferences

/**
 * Android implementation of TaskCacheManager using SharedPreferences.
 */
actual class TaskCacheManager(private val context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences(
        PREFS_NAME,
        Context.MODE_PRIVATE
    )

    actual fun saveTasks(tasksJson: String) {
        prefs.edit().putString(KEY_TASKS, tasksJson).apply()
    }

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

    actual fun clearTasks() {
        prefs.edit().remove(KEY_TASKS).apply()
    }

    /**
     * Check if tasks need refresh due to widget interactions.
     */
    actual fun areTasksDirty(): Boolean {
        return prefs.getBoolean(KEY_DIRTY_FLAG, false)
    }

    /**
     * Mark tasks as dirty (needs refresh).
     * Called when widget modifies task data.
     */
    actual fun markTasksDirty() {
        prefs.edit().putBoolean(KEY_DIRTY_FLAG, true).apply()
    }

    /**
     * Clear the dirty flag after tasks have been refreshed.
     */
    actual fun clearDirtyFlag() {
        prefs.edit().putBoolean(KEY_DIRTY_FLAG, false).apply()
    }

    companion object {
        private const val PREFS_NAME = "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(context: Context): TaskCacheManager {
            return instance ?: synchronized(this) {
                instance ?: TaskCacheManager(context.applicationContext).also { instance = it }
            }
        }
    }
}
