//
//  ActivationCodeGenerationView.swift
//  TrustBuilderMfaSampleApp
//
//  Created by Florent Coudrier on 08/03/2023.
//

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct ActivationCodeGenerationView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var result: String = ""
    
    private var useCaseHandler : TrustBuilderOperationHandler<ActivationCodeGeneration, CredentialProvider>
    @State private var displaySecretCode = false
    @State private var secretCode : String = ""

    init() {
        self.useCaseHandler = TrustBuilderOperationHandler<ActivationCodeGeneration, CredentialProvider>()
    }

    var body: some View {
        VStack {
            Text("Activation code generation")
            TextField("tknAlias", text: $tknAlias).autocapitalization(.none)
            UIUtils.ExecuteUseCaseView(displaySecretCode:$displaySecretCode, SecretCode:$secretCode, newSecretCode : false, setup: setup, execute: execute).disabled(buttonBlock.buttonIsBlocked)
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
                    .textSelection(.enabled)
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    
    func setup(){
        Task.init {
            do{
                let params = ActivationCodeGenerationParams(
                        tknAlias: tknAlias
                )
                let useCase = try TrustBuilderMfaLibHolder.getLibInstance().startActivationCodeGeneration(param: params)
                let setup = await useCase.setup();
                useCaseHandler.loadUseCase(useCase: useCase)
                if (setup.isError == true) {
                    result = UIUtils.formatResponse(response: setup)
                }
                else
                {
                    displaySecretCode = true
                    useCaseHandler.setSetupResult(setupResult: setup.response![0])
                }
            }
            catch{
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
    }
    
    func execute() {
        Task.init {
            buttonBlock.buttonIsBlocked = true
            defer { buttonBlock.buttonIsBlocked = false }
            defer { secretCode = "" }
            do{
                var bytes = Array(secretCode.utf8)
                defer { for i in 0..<bytes.count { bytes[i] = 0 } }
                let credProvider = useCaseHandler.getSetupResult()
                let credValue: CredValue = CredValue(credType: .SECRET_CODE, value: bytes)
                let useCase = useCaseHandler.getUseCase()
                let execute = try await useCase.execute(input: credValue)
                result = UIUtils.formatResponse(response: execute)
            }
            catch{
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
   }
}
