//
//  DeleteSecureTokenView.swift
//  TrustBuilderMfaSampleApp
//
//  Created by TB_COWORKER on 15/06/2023.
//

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct DeleteSecureTokenView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var tknAliasToDelete: String = ""
    @State private var result: String = ""
    
    private var useCaseHandler : TrustBuilderOperationHandler<InAppAuthentication, AuthorizeResponse>
    @State private var displaySecretCode = false
    @State private var secretCode : String = ""

    init() {
        self.useCaseHandler = TrustBuilderOperationHandler<InAppAuthentication, AuthorizeResponse>()
    }

    var body: some View {
        VStack {
            Text("Delete Secure Token")
            TextField("tknAlias", text: $tknAlias).autocapitalization(.none)
            TextField("tknAlias to delete", text: $tknAliasToDelete).autocapitalization(.none)
            UIUtils.ExecuteUseCaseView(displaySecretCode:$displaySecretCode, SecretCode:$secretCode, newSecretCode : false, setup: setup, execute: execute).disabled(buttonBlock.buttonIsBlocked)
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    
    func setup(){
        Task.init {
            do{
                let authorizeResponse = try await SelfcareUtils.authorizeInAppAuthentication(tknAlias: tknAlias);
                let credProvider = authorizeResponse.credentialProvider;
                useCaseHandler.setSetupResult(setupResult: authorizeResponse)
                if (credProvider.credType == CredTypeEnum.SECRET_CODE) {
                    displaySecretCode = true
                } else if (credProvider.credType == CredTypeEnum.BIO) {
                    execute()
                } else {
                    os_log("Invalid cred type: %@", log: .default, type: .error, credProvider.credType as! CVarArg)
                }
            }
            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{
                let authorizeResponse = useCaseHandler.getSetupResult()
                let credProvider = authorizeResponse.credentialProvider
                let credValue = try await CredValueMake.make(tknAlias: tknAlias, credentialProvider: credProvider, secretCode: secretCode)
                let useCase = authorizeResponse.inAppAuthentication
                let execute = try await useCase.execute(input: credValue)
                if (execute.isError) {
                    result = UIUtils.formatResponse(response: execute)
                } else {
                    let userClient = UserClient()
                    let userApiResponse = try! await userClient.deleteSecureToken(secureToken: authorizeResponse.secureToken, bearerToken: execute.response!.code, tknAliasToDelete: tknAliasToDelete)
                    result = UIUtils.formatResponse(response: userApiResponse)
                }
            }
            catch{
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
   }
}
