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

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct AuthenticateView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var sessionId: String = ""
    @State private var result: String = ""
    @State private var displaySecretCode = false
    @State private var secretCode : String = ""
    
    let pub = NotificationCenter.default.publisher(for: Notification.Name("tappedNotification"))
    
    private var useCaseHandler : TrustBuilderOperationHandler<Authentication, CredentialProvider>
    @FocusState var focused: focusedField?
    
    init() {
        self.useCaseHandler = TrustBuilderOperationHandler<Authentication, CredentialProvider>()
    }
    
    var body: some View {
        VStack {
            Text("Authenticate")
            TextField("tknAlias", text: $tknAlias).autocapitalization(.none)
            TextField("sessionId", text: $sessionId).autocapitalization(.none)
            UIUtils.ExecuteUseCaseView(displaySecretCode:$displaySecretCode,  SecretCode:$secretCode, newSecretCode : false, setup: setup, execute: execute).disabled(buttonBlock.buttonIsBlocked)
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
        }.onReceive(pub) { output in
            if let userInfo = output.userInfo, let scope = userInfo["scope"] as? String, scope == AuthScope.AUTH.rawValue {
                tknAlias = userInfo["tknAlias"] as! String
                sessionId = userInfo["authSessionId"] as! String
            }
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    
    func setup(){
        Task.init {
            do{
                let authenticationParams: AuthenticationParams = AuthenticationParams(
                    tknAlias: tknAlias,
                    sessionId: sessionId,
                )
                let authentication = try TrustBuilderMfaLibHolder.getLibInstance().startAuthentication(param: authenticationParams)
                useCaseHandler.loadUseCase(useCase: authentication)
                let setup = await authentication.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 = useCaseHandler.getSetupResult()
                 let credValue = try await CredValueMake.make(tknAlias: tknAlias, credentialProvider: credProvider, secretCode: secretCode)
                 let authentication = useCaseHandler.getUseCase()
                 let execute = try await authentication.execute(input: credValue)
                 result = UIUtils.formatResponse(response: execute)
             }
             catch{
                 os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                 result = String(describing: error)
             }
         }
    }
    enum focusedField {
           case secure, unSecure
       }
}
