package io.trustbuilder.mfa.android.demoapp.screen;

import android.os.Bundle;
import android.util.Log;

import io.trustbuilder.mfa.android.demoapp.R;
import io.trustbuilder.mfa.lib.usecase.IUseCase;
import io.trustbuilder.mfa.lib.usecase.definition.CredValue;
import io.trustbuilder.mfa.lib.usecase.definition.CredentialProvider;
import io.trustbuilder.mfa.lib.usecase.definition.activationcodegeneration.ActivationCodeGeneration;
import io.trustbuilder.mfa.lib.usecase.definition.activationcodegeneration.ActivationCodeGenerationParams;
import io.trustbuilder.mfa.lib.usecase.definition.activationcodegeneration.ActivationCodeGenerationSetupResult;

public class ActivationCodeGenerationActivity extends TrustBuilderAuthenticationActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ActivationCodeGenerationUseCase");
        setTitle(this.getClass().getSimpleName());
        setContentView(R.layout.activity_activation_code_generation);
        this.proceed = this.findViewById(R.id.proceed_ActivationCodeGeneration);
        this.tknAlias = this.findViewById(R.id.tknAlias_ActivationCodeGeneration);
        this.result = this.findViewById(R.id.result_ActivationCodeGeneration);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ActivationCodeGenerationUseCase");
        this.proceed.setOnClickListener(v -> {
            if (checkMandatoryField(tknAlias, "tknAlias")) return;
            ActivationCodeGenerationParams request = new ActivationCodeGenerationParams(tknAlias.getText().toString());
            try {
                ActivationCodeGeneration activationCodeGeneration = mfaLib.startActivationCodeGeneration(request);
                ActivationCodeGenerationSetupResult setupResult = activationCodeGeneration.setup();
                if (setupResult.isError()) {
                    displayJsonResult(setupResult.getError());
                } else {
                    CredentialProvider credentialProvider = setupResult.getResponse().get(0);
                    displayCredentials(credentialProvider.getCredType(), credentialProvider.getCredMode(), credentialProvider.getCredProperties().getBioChallenge(), activationCodeGeneration);
                }
            } catch (Exception e) {
                displayException(e);
            }
        });
    }

    @Override
    protected <T extends IUseCase> void executeUseCase(CredValue cred, T usecase) throws Exception {
        Object obj = usecase.execute(cred);
        displayJsonResult(obj);
    }
}
