summaryrefslogtreecommitdiffstats
path: root/Solsnu.Widget/Utilities/AppGroupManager.swift
blob: 95ff2de6a0754d90a7f203226201f48ecaa2d748 (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
62
63
64
65
66
67
import Foundation

class AppGroupManager {
    static let shared = AppGroupManager()
    static let appGroupID = "group.com.ivarlovlie.solverv"

    private lazy var userDefaults: UserDefaults? = {
        UserDefaults(suiteName: Self.appGroupID)
    }()

    // MARK: - Location Storage

    struct UserLocation: Codable {
        let latitude: Double
        let longitude: Double
        let timestamp: String // ISO 8601
        let isDefaultLocation: Bool
    }

    func saveLocation(_ location: UserLocation) {
        guard let ud = userDefaults else { return }
        if let encoded = try? JSONEncoder().encode(location) {
            ud.set(encoded, forKey: "userLocation")
        }
    }

    func getLocation() -> UserLocation? {
        guard let ud = userDefaults,
              let data = ud.data(forKey: "userLocation"),
              let location = try? JSONDecoder().decode(UserLocation.self, from: data) else {
            return nil
        }
        return location
    }

    // MARK: - Sunrise/Sunset Storage

    struct SunTimes: Codable {
        let date: String // ISO 8601 date only (YYYY-MM-DD)
        let sunrise: String // ISO 8601 datetime
        let sunset: String // ISO 8601 datetime
        let timestamp: String // ISO 8601 when calculated
    }

    func saveSunTimes(_ sunTimes: SunTimes) {
        guard let ud = userDefaults else { return }
        if let encoded = try? JSONEncoder().encode(sunTimes) {
            ud.set(encoded, forKey: "sunTimes")
        }
    }

    func getSunTimes() -> SunTimes? {
        guard let ud = userDefaults,
              let data = ud.data(forKey: "sunTimes"),
              let sunTimes = try? JSONDecoder().decode(SunTimes.self, from: data) else {
            return nil
        }
        return sunTimes
    }

    // MARK: - Helpers

    func clearAllData() {
        userDefaults?.removeObject(forKey: "userLocation")
        userDefaults?.removeObject(forKey: "sunTimes")
    }
}