//
//  MeasurementView.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 13/04/2020.
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
//

import SwiftUI

struct MeasurementsView: View {
    
    @EnvironmentObject private var measurements: Measurements
    
    @Binding var visibility: Bool
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .leading, spacing: 14) {
                    VStack(alignment: .leading, spacing: 8) {
                        Text("App History")
                            .font(.system(.title3, design: .rounded).weight(.bold))
                        Text("Local timeline captured by the app while connected to the meter.")
                            .font(.footnote)
                            .foregroundColor(.secondary)
                    }
                    .padding(18)
                    .meterCard(tint: .blue, fillOpacity: 0.18, strokeOpacity: 0.24)

                    if measurements.power.points.isEmpty {
                        Text("No history samples have been captured yet.")
                            .font(.footnote)
                            .foregroundColor(.secondary)
                            .padding(18)
                            .meterCard(tint: .secondary, fillOpacity: 0.14, strokeOpacity: 0.20)
                    } else {
                        LazyVStack(spacing: 12) {
                            ForEach(measurements.power.points) { point in
                                MeasurementPointView(
                                    power: point,
                                    voltage: measurements.voltage.points[point.id],
                                    current: measurements.current.points[point.id]
                                )
                            }
                        }
                    }
                }
                .padding()
            }
            .background(
                LinearGradient(
                    colors: [.blue.opacity(0.14), Color.clear],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
            .navigationBarItems(
                leading: Button("Done") { visibility.toggle() },
                trailing: Button("Clear") {
                    measurements.reset()
                }
                .foregroundColor(.red)
            )
            .navigationBarTitle("App History", displayMode: .inline)
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}
