File size: 2,367 Bytes
4fc4790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
import SwiftUI
import UIKit

struct GatewayDiscoveryDebugLogView: View {
    @Environment(GatewayConnectionController.self) private var gatewayController
    @AppStorage("gateway.discovery.debugLogs") private var debugLogsEnabled: Bool = false

    var body: some View {
        List {
            if !self.debugLogsEnabled {
                Text("Enable “Discovery Debug Logs” to start collecting events.")
                    .foregroundStyle(.secondary)
            }

            if self.gatewayController.discoveryDebugLog.isEmpty {
                Text("No log entries yet.")
                    .foregroundStyle(.secondary)
            } else {
                ForEach(self.gatewayController.discoveryDebugLog) { entry in
                    VStack(alignment: .leading, spacing: 2) {
                        Text(Self.formatTime(entry.ts))
                            .font(.caption)
                            .foregroundStyle(.secondary)
                        Text(entry.message)
                            .font(.callout)
                            .textSelection(.enabled)
                    }
                    .padding(.vertical, 4)
                }
            }
        }
        .navigationTitle("Discovery Logs")
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button("Copy") {
                    UIPasteboard.general.string = self.formattedLog()
                }
                .disabled(self.gatewayController.discoveryDebugLog.isEmpty)
            }
        }
    }

    private func formattedLog() -> String {
        self.gatewayController.discoveryDebugLog
            .map { "\(Self.formatISO($0.ts)) \($0.message)" }
            .joined(separator: "\n")
    }

    private static let timeFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter
    }()

    private static let isoFormatter: ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        return formatter
    }()

    private static func formatTime(_ date: Date) -> String {
        self.timeFormatter.string(from: date)
    }

    private static func formatISO(_ date: Date) -> String {
        self.isoFormatter.string(from: date)
    }
}