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

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct EnrollSecureTokenView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var code: String = ""
    @State private var result: String = ""
    @State private var displaySecretCode = false
    @State private var secretCode : String = ""
    @State private var newSecretCode = false
    
    private var useCaseHandler : TrustBuilderOperationHandler<SecureTokenEnrollment, CredentialProvider>
    
    init() {
        self.useCaseHandler = TrustBuilderOperationHandler<SecureTokenEnrollment, CredentialProvider>()
    }

    var body: some View {
        VStack {
            Text("Enroll secure token")
            TextField("Code", text: $code).autocapitalization(.allCharacters)
            UIUtils.ExecuteUseCaseView(displaySecretCode:$displaySecretCode, SecretCode:$secretCode, newSecretCode : $newSecretCode.wrappedValue, setup: setup, execute: execute, onCancel: {newSecretCode = false }).disabled(buttonBlock.buttonIsBlocked)
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
                    .textSelection(.enabled)
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    
    func setup(){
        Task.init {
            do{
                let secureTokenEnrollmentParams = SecureTokenEnrollmentParams(
                    code: code
                )
                let secureTokenEnrollment = try TrustBuilderMfaLibHolder.getLibInstance().startSecureTokenEnrollment(param: secureTokenEnrollmentParams)
                useCaseHandler.loadUseCase(useCase: secureTokenEnrollment)
                let setup = await secureTokenEnrollment.setup();
            
                if (setup.isError == true) {
                    result = UIUtils.formatResponse(response: setup)
                }
                else{
                    displaySecretCode = true
                    if(setup.response?.credMode == CredMode.NEW){
                        newSecretCode = true
                    }
                    useCaseHandler.setSetupResult(setupResult: setup.response!)
                }
            }
            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 = "" }
            let credProvider = useCaseHandler.getSetupResult()
            if(credProvider.credType.rawValue == CredType.SECRET_CODE.rawValue)
            {
                var bytes = Array(secretCode.utf8)
                defer { for i in 0..<bytes.count { bytes[i] = 0 } } 
                let credValue = CredValue(credType: credProvider.credType, value: bytes)
                let secureTokenEnrollment = useCaseHandler.getUseCase()
                let execute = await secureTokenEnrollment.execute(input: credValue)
                result = UIUtils.formatResponse(response: execute)
            }
            else{
                os_log("Credential type not allowed", log: .default, type: .error)
            }
        }
    }
}
