//
//  UpdateSecureTokenFriendlyNameView.swift
//  tb-mfa-lib-tests
//
//  Created by inwebo imac on 02/11/2021.
//

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct UpdateSecureTokenFriendlyNameView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var tknName: String = ""
    @State private var result: String = ""

    init() { }

    var body: some View {
        VStack {
            Text("Update secure token friendly name")
            TextField("tknAlias", text: $tknAlias).autocapitalization(.none)
            TextField("tknName", text: $tknName).autocapitalization(.none)
            Button("Execute", action: execute).disabled(buttonBlock.buttonIsBlocked)
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }

    func execute() {
        Task.init {
            buttonBlock.buttonIsBlocked = true
            defer { buttonBlock.buttonIsBlocked = false }
            do {
                let useCase = try TrustBuilderMfaLibHolder.getLibInstance().startSecureTokenFriendlyNameUpdate(param: SecureTokenFriendlyNameUpdateParams(tknAlias: tknAlias, tknName: tknName))
                let response = try await useCase.execute()
                let jsonEncoder = JSONEncoder()
                let jsonData = try jsonEncoder.encode(response)
                result = String(data: jsonData, encoding: String.Encoding.utf8)!
            } catch {
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
    }
}
