//
//  DataGroupRowView.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 10/03/2020.
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
//
// https://www.youtube.com/watch?v=9q209mNDV_4

import SwiftUI

struct DataGroupRowView: View {
    
    var id: UInt8
    var width: CGFloat
    var opacity: Double
    var showsCommands: Bool
    var showsEnergy: Bool
    var highlightsSelection: Bool
    
    @EnvironmentObject private var usbMeter: Meter
    
    var body: some View {
        HStack(spacing: 8) {
            cell(width: width) {
                if showsCommands {
                    Button(action: { usbMeter.selectDataGroup(id: id) }) {
                        Label(usbMeter.dataGroupLabel(for: id), systemImage: "\(id).circle")
                            .labelStyle(.titleAndIcon)
                    }
                    .buttonStyle(.plain)
                } else {
                    Text(usbMeter.dataGroupLabel(for: id))
                        .fontWeight(.semibold)
                }
            }
            
            cell(width: width) {
                Text("\(usbMeter.dataGroupRecords[Int(id)]!.ah.format(decimalDigits: 3))")
                    .monospacedDigit()
            }
            
            if showsEnergy {
                cell(width: width) {
                    Text("\(usbMeter.dataGroupRecords[Int(id)]!.wh.format(decimalDigits: 3))")
                        .monospacedDigit()
                }
            }
            
            if showsCommands {
                cell(width: width) {
                    Button(action: { usbMeter.clear(group: id) }) {
                        Label("Clear", systemImage: "trash")
                            .labelStyle(.iconOnly)
                            .foregroundColor(.red)
                    }
                    .buttonStyle(.plain)
                }
            }
        }
        .padding(10)
        .meterCard(
            tint: highlightsSelection && usbMeter.selectedDataGroup == id ? .accentColor : .secondary,
            fillOpacity: highlightsSelection && usbMeter.selectedDataGroup == id ? 0.22 : 0.08 + opacity * 0.25,
            strokeOpacity: highlightsSelection && usbMeter.selectedDataGroup == id ? 0.32 : 0.16,
            cornerRadius: 16
        )
    }

    private func cell<Content: View>(width: CGFloat, @ViewBuilder content: () -> Content) -> some View {
        content()
            .font(.footnote.weight(.semibold))
            .frame(width: width)
            .frame(minHeight: 40)
            .multilineTextAlignment(.center)
    }
}
