import SwiftUI

struct IdPropertyView: View {

    @Binding
    var id: String

    let title: LocalizedStringKey

    let footer: LocalizedStringKey

    let validation: (String) -> Bool

    let update: (String) -> Void

    @State
    private var newId: String

    init(id: Binding<String>,
         title: LocalizedStringKey = "ID",
         footer: LocalizedStringKey,
         validation: @escaping (String) -> Bool = { _ in true },
         update: @escaping (String) -> Void) {
        self._id = id
        self.title = title
        self.footer = footer
        self.validation = validation
        self.update = update
        self.newId = id.wrappedValue
    }

    private var isValid: Bool {
        validation(newId)
    }

    var body: some View {
        GenericPropertyView(title: title, footer: footer) {
            HStack {
                TextField("", text: $newId)
                    .textFieldStyle(.roundedBorder)
                Spacer()
                Button("Update", action: setNewId)
                    .disabled(!isValid)
            }
        }
    }

    private func setNewId() {
        update(newId)
        // In case of failure, resets the id
        // In case of update, sets to potentially modified id
        DispatchQueue.main.async {
            newId = id
        }
    }
}
