//
//  RegisterBiokeyView.swift
//  TrustBuilderMfaSampleApp
//
//  Created by Ludovic Lefevre on 23/05/2023.
//

import Foundation
import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct RegisterBiokeyView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var result: String = ""
    @State private var displaySecretCode = false
    @State private var secretCode : String = ""
    @State private var disclaimer : String = "disclaimer"
    
    private var useCaseHandler : TrustBuilderOperationHandler<BiokeyRegistration, BiokeyRegistrationData>
    
    init() {
        self.useCaseHandler = TrustBuilderOperationHandler<BiokeyRegistration, BiokeyRegistrationData>()
    }
    
    var body: some View {
        VStack {
            Text("RegisterBiokey")
            Text("Disclamer : " + disclaimer)
            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)
        }
        .buttonStyle(.bordered)
        .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    
    func setup() {
        Task.init {
            do{
                let params = BiokeyRegistrationParams(
                    tknAlias: tknAlias
                )
                let biokey = try TrustBuilderMfaLibHolder.getLibInstance().startBiokeyRegistration(param: params)
                useCaseHandler.loadUseCase(useCase: biokey)
                let setup = await biokey.setup();
                if (setup.isError == true) {
                    result = UIUtils.formatResponse(response: setup)
                } else
                {
                    displaySecretCode = 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 = "" } 
            do {
                let cryptoTools:GeneratorCryptoTools = GeneratorCryptoTools()
                let keypair = try cryptoTools.generateRSAKeyPair(keySize: 3072)
                let decodedPublicKey = Data(base64Encoded: keypair.publicKey)
                let signedBioChallenge = GeneratorCryptoTools.signData(data: useCaseHandler.getSetupResult().bioChallenge!, privateKey: keypair.privateKey)
                var bytes = Array(secretCode.utf8)
                defer { for i in 0..<bytes.count { bytes[i] = 0 } }
                let credValue: CredValue = CredValue(credType: .SECRET_CODE, value: bytes)
                let bioparams : BiokeyRegistrationExecuteParams = BiokeyRegistrationExecuteParams(credValue: credValue, disclaimer: Data(disclaimer.utf8), bioPubKey: decodedPublicKey!, signedBioChallenge: signedBioChallenge)
                let biokey = useCaseHandler.getUseCase()
                let execute = try await biokey.execute(input: bioparams)
                result = UIUtils.formatResponse(response: execute)
                if(execute.isError == false){
                    try BioKeyStorage().save(tknAlias: tknAlias, privateKey: Data(keypair.privateKey.utf8))
                }
            } catch {
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
    }
}
