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

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

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.securetokenenrollment.SecureTokenEnrollment;
import io.trustbuilder.mfa.lib.usecase.definition.securetokenenrollment.SecureTokenEnrollmentParams;
import io.trustbuilder.mfa.lib.usecase.definition.securetokenenrollment.SecureTokenEnrollmentSetupResult;

public class SecureTokenEnrollmentActivity extends TrustBuilderAuthenticationActivity {
    private EditText code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: SecureTokenEnrollmentUseCase");
        setTitle(this.getClass().getSimpleName());
        setContentView(R.layout.activity_enroll_secure_token);
        this.proceed = this.findViewById(R.id.proceed_EnrollSecureToken);
        this.code = this.findViewById(R.id.code_EnrollSecureToken);
        this.result = this.findViewById(R.id.result_EnrollSecureToken);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: SecureTokenEnrollmentUseCase");
        this.proceed.setOnClickListener((v) -> {
            if (checkMandatoryField(code, "code")) return;
            SecureTokenEnrollmentParams request = new SecureTokenEnrollmentParams(code.getText().toString());
            try {
                SecureTokenEnrollment enrollSecureToken = mfaLib.startSecureTokenEnrollment(request);
                SecureTokenEnrollmentSetupResult setupResult = enrollSecureToken.setup();
                if (setupResult.isError()) {
                    displayJsonResult(setupResult.getError());
                } else {
                    CredentialProvider credentialProvider = setupResult.getResponse();
                    displayCredentials(credentialProvider.getCredType(), credentialProvider.getCredMode(), credentialProvider.getCredProperties().getBioChallenge(), enrollSecureToken);
                }
            } 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);
    }
}