package com.tt.honeyDue.data

import platform.Foundation.NSUserDefaults

/**
 * iOS implementation of PersistenceManager using NSUserDefaults.
 */
actual class PersistenceManager {
    private val defaults = NSUserDefaults.standardUserDefaults

    actual fun save(key: String, value: String) {
        defaults.setObject(value, forKey = key)
        defaults.synchronize()
    }

    actual fun load(key: String): String? {
        return defaults.stringForKey(key)
    }

    actual fun remove(key: String) {
        defaults.removeObjectForKey(key)
        defaults.synchronize()
    }

    actual fun clear() {
        // Get all keys with our prefix and remove them
        val dict = defaults.dictionaryRepresentation()
        dict.keys.forEach { key ->
            val keyStr = key as? String ?: return@forEach
            if (keyStr.startsWith("dm_")) {
                defaults.removeObjectForKey(keyStr)
            }
        }
        defaults.synchronize()
    }

    companion object {
        private val instance by lazy { PersistenceManager() }

        fun getInstance(): PersistenceManager = instance
    }
}
