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

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct InAppAuthenticateView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var sessionId: String = ""
    @State private var scope: String = ""
    @State private var result: String = ""
    @State private var displaySecretCode = false
    @State private var secretCode : String = ""

    private var useCaseHandler = TrustBuilderOperationHandler<InAppAuthentication, CredentialProvider>()

    init() { }

    var body: some View {
        VStack {
            Text("In App Authenticate")
            TextField("tknAlias", text: $tknAlias).autocapitalization(.none)
            TextField("sessionId", text: $sessionId).autocapitalization(.none)
            TextField("scope", text: $scope).autocapitalization(.allCharacters)
            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 inAppAuthenticationParams: InAppAuthenticationParams = InAppAuthenticationParams(
                    tknAlias: tknAlias,
                    sessionId: sessionId,
                    scope: AuthScope(rawValue: scope) ?? AuthScope.SESSION
                )
                let inAppAuthentication = try TrustBuilderMfaLibHolder.getLibInstance().startInAppAuthentication(param: inAppAuthenticationParams)
                useCaseHandler.loadUseCase(useCase: inAppAuthentication)
                let setup = await inAppAuthentication.setup();
                if (setup.isError == true) {
                    result = UIUtils.formatResponse(response: setup)
                }
                else
                {
                    let setupResultHandler = CredentialProviderHandler()
                    let resolvedCredentialProvider = setupResultHandler.resolveCredentialFromList(listCredProvider: setup.response!)
                    useCaseHandler.setSetupResult(setupResult : resolvedCredentialProvider)
                    if (resolvedCredentialProvider.credType == CredTypeEnum.SECRET_CODE) {
                        displaySecretCode = true
                    } else if (resolvedCredentialProvider.credType == CredTypeEnum.BIO) {
                        execute()
                    } else {
                        os_log("Invalid cred type: %@", log: .default, type: .error, resolvedCredentialProvider.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 credProvider : CredentialProvider = useCaseHandler.getSetupResult()
                let credValue = try await CredValueMake.make(tknAlias: tknAlias, credentialProvider: credProvider, secretCode: secretCode)
                let inAppAuthentication = useCaseHandler.getUseCase()
                let execute = try await inAppAuthentication.execute(input: credValue)
                result = UIUtils.formatResponse(response: execute)
            }
            catch{
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
    }
}
