// // PaxCounterLog.swift // Meshtastic // // Created by Garth Vander Houwen on 2/25/24. // import SwiftUI import Charts import OSLog struct PaxCounterLog: View { @Environment(\.managedObjectContext) var context @EnvironmentObject var bleManager: BLEManager @EnvironmentObject var updateCoreDataController: UpdateCoreDataController @State private var isPresentingClearLogConfirm: Bool = false @State var isExporting = false @State var exportString = "" @State private var bleChartColor: Color = .blue @State private var wifiChartColor: Color = .orange @State private var paxChartColor: Color = .green @ObservedObject var node: NodeInfoEntity var body: some View { VStack { if node.hasPax { let oneWeekAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date()) let pax = node.pax?.reversed() as? [PaxCounterEntity] ?? [] let chartData = pax .filter { $0.time != nil && $0.time! >= oneWeekAgo! } .sorted { $0.time! < $1.time! } let maxValue = (chartData.map { $0.wifi }.max() ?? 0) + (chartData.map { $0.ble }.max() ?? 0) + 5 if chartData.count > 0 { GroupBox(label: Label("\(pax.count) Readings Total", systemImage: "chart.xyaxis.line")) { Chart { ForEach(chartData, id: \.self) { point in Plot { PointMark( x: .value("x", point.time!), y: .value("y", (point.wifi + point.ble)) ) } .accessibilityLabel("paxcounter.total") .accessibilityValue("X: \(point.time!), Y: \(point.wifi + point.ble)") .foregroundStyle(paxChartColor) .interpolationMethod(.cardinal) Plot { PointMark( x: .value("x", point.time!), y: .value("y", point.wifi) ) } .accessibilityLabel("paxcounter.wifi") .accessibilityValue("X: \(point.time!), Y: \(point.wifi)") .foregroundStyle(wifiChartColor) Plot { PointMark( x: .value("x", point.time!), y: .value("y", point.ble) ) } .accessibilityLabel("paxcounter.ble") .accessibilityValue("X: \(point.time!), Y: \(point.ble)") .foregroundStyle(bleChartColor) } } .chartXAxis(content: { AxisMarks(position: .top) }) .chartXAxis(.automatic) .chartYScale(domain: 0...maxValue) .chartForegroundStyleScale([ "paxcounter.ble".localized: .blue, "paxcounter.wifi".localized: .orange, "paxcounter.total".localized: .green ]) .chartLegend(position: .automatic, alignment: .bottom) } .frame(minHeight: 250) } let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMMddjmma", options: 0, locale: Locale.current) let dateFormatString = (localeDateFormat ?? "MM/dd/YY j:mma").replacingOccurrences(of: ",", with: "") if UIScreen.main.bounds.size.width > 768 && (UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac) { // Add a table for mac and ipad Table(pax) { TableColumn("paxcounter.ble") { pc in Text("\(pc.ble)") } TableColumn("paxcounter.wifi") { pc in Text("\(pc.wifi)") } TableColumn("paxcounter.total") { pc in Text("\(pc.wifi + pc.ble)") } TableColumn("uptime") { pc in let now = Date.now let later = now + TimeInterval(pc.uptime) let components = (now..