import SwiftUI

struct SettingsKeyItemLink: View {

    let type: KeyManagement.KeyType

    let footnote: String

    @EnvironmentObject
    private var keys: KeyManagement

    @State
    private var keyText = "..."

    var body: some View {
        NavigationLink {
            SettingsKeyInputView(
                type: type,
                footnote: footnote)
            .environmentObject(keys)
        } label: {
            SettingsListTextItem(
                title: type.displayName,
                value: keyText)
            .onAppear(perform: updateKeyText)
        }
        .buttonStyle(PlainButtonStyle())
    }

    private func updateKeyText() {
        Task {
            let key = keys.get(type)?.displayString ?? "Not set"
            DispatchQueue.main.async {
                keyText = key
            }
        }
    }
}

struct SettingsKeyItemLink_Previews: PreviewProvider {
    static var previews: some View {
        SettingsKeyItemLink(
            type: .deviceKey,
            footnote: "Some text describing the purpose of the key.")
        .environmentObject(KeyManagement())
    }
}
