import Foundation import Observation import DevPlaceSwiftSDK extension NotificationSettingsView { @Observable final class ViewModel { let api: DevPlaceApi var username: String? var groupingEnabled = true var throttlingEnabled = true var telegramPaired = false var preferences: [NotificationPreference] = [] var isLoaded = false var alertMessage: AlertMessage = .none() init(api: DevPlaceApi) { self.api = api } var hasCustomizedPreferences: Bool { preferences.contains { $0.customized } } func isEnabled(_ channel: NotificationChannel, in preference: NotificationPreference) -> Bool { switch channel { case .inApp: preference.inApp case .push: preference.push case .telegram: preference.telegram } } func load() async { do { let settings = try await api.notificationSettings() username = settings.user.username groupingEnabled = settings.groupingEnabled throttlingEnabled = settings.throttlingEnabled telegramPaired = settings.telegramPaired preferences = settings.preferences isLoaded = true } catch { alertMessage = .presentedError(error) } } func setGrouping(_ enabled: Bool) async { guard let username else { return } groupingEnabled = enabled do { try await api.setNotificationGrouping(username: username, enabled: enabled) } catch { alertMessage = .presentedError(error) await load() } } func setThrottling(_ enabled: Bool) async { guard let username else { return } throttlingEnabled = enabled do { try await api.setNotificationThrottling(username: username, enabled: enabled) } catch { alertMessage = .presentedError(error) await load() } } func set(_ channel: NotificationChannel, enabled: Bool, forKey key: String) async { guard let username else { return } preferences = preferences.map { preference in preference.key == key ? updated(preference, channel: channel, enabled: enabled) : preference } do { try await api.setNotificationPreference( username: username, notificationType: key, channel: channel, enabled: enabled, ) } catch { alertMessage = .presentedError(error) await load() } } func resetPreferences() async { guard let username else { return } do { try await api.resetNotificationPreferences(username: username) } catch { alertMessage = .presentedError(error) } await load() } private func updated(_ preference: NotificationPreference, channel: NotificationChannel, enabled: Bool) -> NotificationPreference { NotificationPreference( key: preference.key, label: preference.label, description: preference.description, inApp: channel == .inApp ? enabled : preference.inApp, push: channel == .push ? enabled : preference.push, telegram: channel == .telegram ? enabled : preference.telegram, customized: true, ) } } }