summaryrefslogtreecommitdiff
path: root/Shared/ContributionWidgetContext.swift
blob: 33fed77829ad914c44e12e50ca6054d2b02360b1 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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(
        accountID: String? = ActiveAccountContextStore.load(),
        defaults: UserDefaults? = sharedDefaults()
    ) -> String? {
        defaults?.string(forKey: scopedActorKey(for: accountID))
    }

    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,
        accountID: String? = ActiveAccountContextStore.load(),
        defaults: UserDefaults? = sharedDefaults()
    ) {
        defaults?.set(actor, forKey: scopedActorKey(for: accountID))
        reloadWidgetTimelines()
    }

    static func clear(
        accountID: String? = ActiveAccountContextStore.load(),
        defaults: UserDefaults? = sharedDefaults()
    ) {
        defaults?.removeObject(forKey: scopedActorKey(for: accountID))
        reloadWidgetTimelines()
    }

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

    private static func scopedActorKey(for accountID: String?) -> String {
        guard let accountID, !accountID.isEmpty else { return actorKey }
        return "\(actorKey).\(accountID)"
    }

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