summaryrefslogtreecommitdiff
path: root/Shared/ContributionWidgetContext.swift
blob: 240469852f25beff74cff56eb3547ea49ae7b82e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Foundation
#if canImport(WidgetKit)
import WidgetKit
#endif

enum ContributionGraphWidgetConfiguration {
    static let kind = "ContributionGraphWidget"
}

enum ContributionWidgetContextStore {
    private static let actorKey = "contributionWidget.actor"
    private static let enabledKey = "contributionWidget.enabled"

    static func loadActor(defaults: UserDefaults? = sharedDefaults()) -> String? {
        defaults?.string(forKey: actorKey)
    }

    static func isEnabled(defaults: UserDefaults? = sharedDefaults()) -> Bool {
        defaults?.object(forKey: enabledKey) == nil ? true : defaults?.bool(forKey: enabledKey) ?? true
    }

    static func setEnabled(_ enabled: Bool, defaults: UserDefaults? = sharedDefaults()) {
        defaults?.set(enabled, forKey: enabledKey)
        reloadWidgetTimelines()
    }

    static func saveActor(_ actor: String, defaults: UserDefaults? = sharedDefaults()) {
        defaults?.set(actor, forKey: actorKey)
        reloadWidgetTimelines()
    }

    static func clear(defaults: UserDefaults? = sharedDefaults()) {
        defaults?.removeObject(forKey: actorKey)
        reloadWidgetTimelines()
    }

    private static func sharedDefaults() -> UserDefaults? {
        UserDefaults(suiteName: HutchAppGroup.identifier)
    }

    private static func reloadWidgetTimelines() {
        #if canImport(WidgetKit)
        WidgetCenter.shared.reloadTimelines(ofKind: ContributionGraphWidgetConfiguration.kind)
        #endif
    }
}