//
//  SensorView.swift
//  Gran Fondo
//
//  Created by Willem L. Middelkoop on 01/05/2024.
//

import SwiftUI

struct SensorView: View {
    @Binding var sensors: [Sensor]
    @ObservedObject var bluetoothManager: BluetoothManager
    @Environment(\.presentationMode) var presentationMode
    @State private var isEditing = true  // State to control edit mode

    var body: some View {
        
        NavigationView {
            VStack{
                Text("Connect to sensors such as speed, cadence, power, and heart rate. Supported sensors within Bluetooth range are automatically shown in the list below. \n\nEnable a sensor by tapping the circle. Sensors with green checkmarks are enabled.\n\nPrioritize a sensor by moving it ot the top. Gran Fondo will automatically use the first sensor of a given type it detects.")
                    .padding()
                
                List {
                    ForEach(sensors, id: \.id) { sensor in
                        HStack {
                            Image(systemName: sensor.isConnected ? "antenna.radiowaves.left.and.right" : "antenna.radiowaves.left.and.right.slash")
                                .foregroundColor(sensor.isConnected ? .green : .gray)
                            Text(sensor.name)
                            Spacer()
                            Image(systemName: sensor.isSelected ? "checkmark.circle.fill" : "circle")
                                .foregroundColor(sensor.isSelected ? .green : .gray)
                                .onTapGesture {
                                    if let index = sensors.firstIndex(where: { $0.id == sensor.id }) {
                                        //sensors[index].isSelected.toggle()
                                        bluetoothManager.toggleSensorSelection(for: sensors[index])
                                    }
                                }
                        }
                    }
                    .onMove(perform: move)
                }
                .navigationTitle("Sensors")
                .navigationBarItems(trailing: Button("Done") {
                    presentationMode.wrappedValue.dismiss()
                })
                .environment(\.editMode, .constant(isEditing ? EditMode.active : EditMode.inactive)) // Use a constant to force the edit mode
            }
        }
    }
    
    func move(from source: IndexSet, to destination: Int) {
        sensors.move(fromOffsets: source, toOffset: destination)
        bluetoothManager.scanForSensors()
    }
}

