summaryrefslogtreecommitdiff
path: root/Hutch/Views/Lookup/LookupHistoryStore.swift
blob: e127970d6dbcc16a8f221e93436ef57cf85fc819 (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

struct LookupHistoryEntry: Codable, Hashable, Identifiable, Sendable {
    let type: LookupType
    let query: String
    let createdAt: Date

    var id: String {
        "\(type.rawValue):\(query)"
    }
}

enum LookupHistoryStore {
    private static let maximumEntries = 20

    static func load(defaults: UserDefaults = .standard) -> [LookupHistoryEntry] {
        guard let data = defaults.data(forKey: AppStorageKeys.lookupHistory) else {
            return []
        }

        do {
            return try JSONDecoder().decode([LookupHistoryEntry].self, from: data)
        } catch {
            defaults.removeObject(forKey: AppStorageKeys.lookupHistory)
            return []
        }
    }

    static func record(
        type: LookupType,
        query: String,
        defaults: UserDefaults = .standard,
        now: Date = .now
    ) {
        let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !normalizedQuery.isEmpty else { return }

        var entries = load(defaults: defaults)
        entries.removeAll { $0.type == type && $0.query == normalizedQuery }
        entries.insert(
            LookupHistoryEntry(type: type, query: normalizedQuery, createdAt: now),
            at: 0
        )

        if entries.count > maximumEntries {
            entries = Array(entries.prefix(maximumEntries))
        }

        save(entries, defaults: defaults)
    }

    static func clear(defaults: UserDefaults = .standard) {
        defaults.removeObject(forKey: AppStorageKeys.lookupHistory)
    }

    private static func save(_ entries: [LookupHistoryEntry], defaults: UserDefaults) {
        guard let data = try? JSONEncoder().encode(entries) else { return }
        defaults.set(data, forKey: AppStorageKeys.lookupHistory)
    }
}