package com.tt.honeyDue.storage

import com.tt.honeyDue.models.CustomTask
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString

/**
 * Task cache storage that provides a unified interface for accessing platform-specific
 * persistent storage. This allows tasks to persist across app restarts for offline access.
 */
object TaskCacheStorage {
    private var cacheManager: TaskCacheManager? = null
    private val json = Json { ignoreUnknownKeys = true }

    /**
     * Initialize TaskCacheStorage with a platform-specific TaskCacheManager.
     * This should be called once during app initialization.
     */
    fun initialize(manager: TaskCacheManager) {
        cacheManager = manager
    }

    private fun ensureInitialized() {
        if (cacheManager == null) {
            cacheManager = getPlatformTaskCacheManager()
        }
    }

    fun saveTasks(tasks: List<CustomTask>) {
        ensureInitialized()
        try {
            val tasksJson = json.encodeToString(tasks)
            cacheManager?.saveTasks(tasksJson)
        } catch (e: Exception) {
            println("Error saving tasks to cache: ${e.message}")
        }
    }

    fun getTasks(): List<CustomTask>? {
        ensureInitialized()
        return try {
            val tasksJson = cacheManager?.getTasks()
            if (tasksJson != null) {
                json.decodeFromString<List<CustomTask>>(tasksJson)
            } else {
                null
            }
        } catch (e: Exception) {
            println("Error loading tasks from cache: ${e.message}")
            null
        }
    }

    fun clearTasks() {
        ensureInitialized()
        cacheManager?.clearTasks()
    }

    /**
     * Check if tasks need refresh due to widget interactions.
     */
    fun areTasksDirty(): Boolean {
        ensureInitialized()
        return cacheManager?.areTasksDirty() ?: false
    }

    /**
     * Mark tasks as dirty (needs refresh).
     * Called when widget modifies task data.
     */
    fun markTasksDirty() {
        ensureInitialized()
        cacheManager?.markTasksDirty()
    }

    /**
     * Clear the dirty flag after tasks have been refreshed.
     */
    fun clearDirtyFlag() {
        ensureInitialized()
        cacheManager?.clearDirtyFlag()
    }
}

/**
 * Platform-specific function to get the default TaskCacheManager instance.
 * For platforms that don't require context (web, iOS, JVM), returns singleton.
 * For Android, must be initialized via initialize() method before use.
 */
internal expect fun getPlatformTaskCacheManager(): TaskCacheManager?
