import SwiftUI
import CryptoKit

struct SettingsKeyInputView: View {

    let type: KeyManagement.KeyType

    @State
    private var text: String = ""

    let footnote: String

    @EnvironmentObject
    private var keys: KeyManagement

    private var hasKey: Bool {
        keys.has(type)
    }

    private var displayText: String {
        keys.get(type)?.displayString ?? "-"
    }

    private var copyText: String {
        guard let key = keys.get(type)?.data else {
            return ""
        }
        guard type.usesHashing else {
            return key.hexEncoded
        }
        return SHA256.hash(data: key).hexEncoded
    }

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                TextField(type.displayName, text: $text)
                    .onSubmit(validateText)
                    .foregroundColor(.accentColor)
                Text(footnote)
                    .font(.footnote)
                    .foregroundColor(.secondary)
            }
            .navigationTitle(type.displayName)
            .onAppear {
                if text == "" {
                    text = displayText
                    print("Text inserted")
                }
            }
        }
    }

    private func validateText() {
        let cleanText = text.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        guard let keyData = Data(fromHexEncodedString: cleanText) else {
            print("Invalid key string")
            return
        }
        let keyLength = type.keyLength.bitCount
        guard keyData.count * 8 == keyLength else {
            print("Invalid key length \(keyData.count * 8) bits, expected \(keyLength) (Input: '\(text)')")
            return
        }
        keys.save(type, data: keyData)
        print("Key \(type) saved")
    }
}

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