summaryrefslogtreecommitdiff
path: root/DomainDig/DomainViewModel+Widget.swift
blob: 59b28e06b87e6e4ca36b4a5d92bad6e6d5e693e2 (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
import Foundation
import WidgetKit

extension DomainViewModel {
    /// Publishes the current portfolio state to the App Group container so the
    /// widget can render it, then asks WidgetKit to refresh its timelines.
    func refreshWidgetData() {
        let data = portfolioDashboardData
        let snapshot = data.snapshot

        let ordered = data.domainStates.sorted { lhs, rhs in
            if lhs.trackedDomain.isPinned != rhs.trackedDomain.isPinned {
                return lhs.trackedDomain.isPinned
            }
            return lhs.health.widgetSeverityRank > rhs.health.widgetSeverityRank
        }

        let domains = ordered.prefix(6).map { state in
            DomainDigWidgetDomain(
                domain: state.trackedDomain.domain,
                isPinned: state.trackedDomain.isPinned,
                status: state.health.widgetStatus,
                certDaysRemaining: state.certificateDaysRemaining,
                lastChange: state.lastChangeDate
            )
        }

        DomainDigWidgetStore.write(
            DomainDigWidgetData(
                generatedAt: Date(),
                totalDomains: snapshot.totalDomains,
                healthyCount: snapshot.healthyCount,
                warningCount: snapshot.warningCount,
                criticalCount: snapshot.criticalCount,
                expiringSoonCount: snapshot.expiringSoonCount,
                unreachableCount: snapshot.unreachableCount,
                domains: Array(domains)
            )
        )
        WidgetCenter.shared.reloadAllTimelines()
    }
}

private extension DomainHealth {
    var widgetStatus: DomainDigWidgetStatus {
        switch self {
        case .healthy: return .healthy
        case .warning: return .warning
        case .critical: return .critical
        }
    }

    var widgetSeverityRank: Int {
        switch self {
        case .healthy: return 0
        case .warning: return 1
        case .critical: return 2
        }
    }
}