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

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct ChangeSecretCodeView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var tknAlias: String = ""
    @State private var result: String = ""
    @State private var displaySecretCode = false
    @State private var oldSecretCode : String = ""
    @State private var newSecretCode : String = ""
    private var useCaseHandler : TrustBuilderOperationHandler<SecretCodeChange,CredentialProvider>

    init() {
        self.useCaseHandler = TrustBuilderOperationHandler<SecretCodeChange, CredentialProvider>()
    }

    var body: some View {
        VStack {
            Text("Change secret code")
            TextField("tknAlias", text: $tknAlias).autocapitalization(.none)
            Button("Execute", action: setup).alert("Secret Code ", isPresented: $displaySecretCode, actions: {
                    SecureField("Old secret code ", text: $oldSecretCode )
                    SecureField("New secret code ", text: $newSecretCode )
                    Button("Validate", action: execute)
                    Button("Cancel", role: .cancel, action: {oldSecretCode = ""; newSecretCode = ""}).disabled(buttonBlock.buttonIsBlocked)
                }, message: {
                    Text("Please enter your old secret code  and your new secret code .")
                })
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }
    
    func setup() {
        Task.init {
            do {
                let secretCodeChangeParams: SecretCodeChangeParams = SecretCodeChangeParams(
                        tknAlias: tknAlias
                )
                let secretCodeChange = try TrustBuilderMfaLibHolder.getLibInstance().startSecretCodeChange(param: secretCodeChangeParams)
                let setup = await secretCodeChange.setup();
                useCaseHandler.loadUseCase(useCase: secretCodeChange)
                if (setup.isError == true) {
                    result = UIUtils.formatResponse(response: setup)
                } else {
                    displaySecretCode = true
                }
            } 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 { oldSecretCode = ""; newSecretCode = "" }
            var oldBytes = Array(oldSecretCode.utf8)
            var newBytes = Array(newSecretCode.utf8)
            defer {
                for i in 0..<oldBytes.count { oldBytes[i] = 0 }
                for i in 0..<newBytes.count { newBytes[i] = 0 }
            }
            let currentCredValue: CredValue = CredValue(credType: .SECRET_CODE, value: oldBytes)
            let newCredValue: CredValue = CredValue(credType: .SECRET_CODE, value: newBytes)
            let credValues: CredValues = CredValues(currentCredValue: currentCredValue, newCredValue: newCredValue)
            let secretCodeChange = useCaseHandler.getUseCase()
            let execute = try await secretCodeChange.execute(input: credValues)
            result = UIUtils.formatResponse(response: execute)
        }
    }
}


