import SwiftUI
import CryptoKit

struct SingleKeyView: View {

    @State
    private var needRefresh = false

    @Binding
    var keyManager: KeyManagement

    let type: KeyManagement.KeyType

    private var generateText: String {
        hasKey ? "Regenerate" : "Generate"
    }

    var hasKey: Bool {
        keyManager.has(type)
    }

    var content: String {
        keyManager.get(type)?.displayString ?? "-"
    }

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

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(type.displayName)
                .bold()
            Text(needRefresh ? content : content)
                .font(.system(.body, design: .monospaced))
                .foregroundColor(.secondary)
            HStack() {
                Button(generateText) {
                    keyManager.generate(type)
                    needRefresh.toggle()
                }
                .padding()

                Button(type.usesHashing ? "Copy hash" : "Copy") {
                    UIPasteboard.general.string = copyText
                }
                .disabled(!hasKey)
                .padding()
                Spacer()
            }
        }
    }
}

struct SingleKeyView_Previews: PreviewProvider {
    static var previews: some View {
        SingleKeyView(
            keyManager: .constant(KeyManagement()),
            type: .deviceKey)
    }
}
