// // DataStateManager.swift import Foundation /// Manages the overall data state timestamp for sync purposes. This tracks when any data in the /// local database was last modified, independent of individual entity timestamps. class DataStateManager { private let userDefaults = UserDefaults.standard private enum Keys { static let lastModified = "openclimb_data_last_modified" static let initialized = "openclimb_data_state_initialized" } /// Shared instance for app-wide use static let shared = DataStateManager() private init() { // Initialize with current timestamp if this is the first time if !isInitialized() { print("DataStateManager: First time initialization") // Set initial timestamp to a very old date so server data will be considered newer let epochTime = "1970-01-01T00:00:00.000Z" userDefaults.set(epochTime, forKey: Keys.lastModified) markAsInitialized() print("DataStateManager initialized with epoch timestamp: \(epochTime)") } else { print("DataStateManager: Already initialized, current timestamp: \(getLastModified())") } } /// Updates the data state timestamp to the current time. Call this whenever any data is modified /// (create, update, delete). func updateDataState() { let now = ISO8601DateFormatter().string(from: Date()) userDefaults.set(now, forKey: Keys.lastModified) print("📝 iOS Data state updated to: \(now)") } /// Gets the current data state timestamp. This represents when any data was last modified /// locally. func getLastModified() -> String { if let storedTimestamp = userDefaults.string(forKey: Keys.lastModified) { print("📅 iOS DataStateManager returning stored timestamp: \(storedTimestamp)") return storedTimestamp } // If no timestamp is stored, return epoch time to indicate very old data // This ensures server data will be considered newer than uninitialized local data let epochTime = "1970-01-01T00:00:00.000Z" print("⚠️ No data state timestamp found - returning epoch time: \(epochTime)") return epochTime } /// Sets the data state timestamp to a specific value. Used when importing data from server to /// sync the state. func setLastModified(_ timestamp: String) { userDefaults.set(timestamp, forKey: Keys.lastModified) print("Data state set to: \(timestamp)") } /// Resets the data state (for testing or complete data wipe). func reset() { userDefaults.removeObject(forKey: Keys.lastModified) userDefaults.removeObject(forKey: Keys.initialized) print("Data state reset") } /// Checks if the data state has been initialized. private func isInitialized() -> Bool { return userDefaults.bool(forKey: Keys.initialized) } /// Marks the data state as initialized. private func markAsInitialized() { userDefaults.set(true, forKey: Keys.initialized) } /// Gets debug information about the current state. func getDebugInfo() -> String { return "DataState(lastModified=\(getLastModified()), initialized=\(isInitialized()))" } }