package com.tt.honeyDue.storage

import platform.Foundation.NSUserDefaults
import kotlin.concurrent.Volatile

/**
 * iOS implementation of TaskCacheManager using NSUserDefaults.
 * Note: iOS widget dirty flag is handled by native Swift WidgetDataManager
 * using App Groups shared storage, but we provide these methods for KMM compatibility.
 */
actual class TaskCacheManager {
    private val userDefaults = NSUserDefaults.standardUserDefaults

    actual fun saveTasks(tasksJson: String) {
        userDefaults.setObject(tasksJson, KEY_TASKS)
        userDefaults.synchronize()
    }

    actual fun getTasks(): String? {
        return userDefaults.stringForKey(KEY_TASKS)
    }

    actual fun clearTasks() {
        userDefaults.removeObjectForKey(KEY_TASKS)
        userDefaults.synchronize()
    }

    /**
     * Check if tasks need refresh due to widget interactions.
     * Note: iOS primarily uses native Swift WidgetDataManager for this.
     */
    actual fun areTasksDirty(): Boolean {
        return userDefaults.boolForKey(KEY_DIRTY_FLAG)
    }

    /**
     * Mark tasks as dirty (needs refresh).
     */
    actual fun markTasksDirty() {
        userDefaults.setBool(true, KEY_DIRTY_FLAG)
        userDefaults.synchronize()
    }

    /**
     * Clear the dirty flag after tasks have been refreshed.
     */
    actual fun clearDirtyFlag() {
        userDefaults.setBool(false, KEY_DIRTY_FLAG)
        userDefaults.synchronize()
    }

    companion object {
        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 }
            }
        }
    }
}

// Helper function for synchronization on iOS
private fun <T> synchronized(lock: Any, block: () -> T): T {
    return block()
}
