/*
 * Created by WebId Solutions GmbH | www.webid-solutions.de.
 * See the file "LICENSE" for the full license governing this code.
 */
package de.webidsolutions.metaplugindemo.tasks;

import android.os.AsyncTask;

import java.io.IOException;

import de.webidsolutions.mobile_app.sdk.AccessDeniedException;
import de.webidsolutions.mobile_app.sdk.EidIdentRequiredException;
import de.webidsolutions.mobile_app.sdk.IWebIdMobileAppSdk;
import de.webidsolutions.mobile_app.sdk.IdentNotSupportedException;
import de.webidsolutions.mobile_app.sdk.LegalTermsConfirmationMissingException;
import de.webidsolutions.mobile_app.sdk.ServiceUnavailableException;
import de.webidsolutions.mobile_app.sdk.UserActionNotFinishedException;
import de.webidsolutions.mobile_app.sdk.UserActionNotFoundException;
import de.webidsolutions.mobile_app.sdk.domain.VerifyActionIdResult;

/**
 * A asynchronous call for sdkInstance.verifyActionId(params[0]).
 * Only implemented inside an AsyncTask for demo purposes.
 * Can be also be done via other means, e.g. coroutines.
 */
public class VerifyActionIdTask extends AsyncTask<String, Void, AsyncTaskResult<VerifyActionIdResult>> {
    private IOnPostExecuteCallback<AsyncTaskResult<VerifyActionIdResult>> iVerifyActionIdInternalOnPostExecuteCallback;
    private final IWebIdMobileAppSdk sdkInstance;

    @Override
    protected AsyncTaskResult<VerifyActionIdResult> doInBackground(String... params) {

        String apiResult;

        try {

            return new AsyncTaskResult<>(sdkInstance.verifyActionId(params[0]), "success");

        } catch (
                IdentNotSupportedException |
                        UserActionNotFinishedException |
                        AccessDeniedException |
                        EidIdentRequiredException |
                        LegalTermsConfirmationMissingException |
                        IOException |
                        ServiceUnavailableException |
                        UserActionNotFoundException e
        ) {
            apiResult = e.getClass().getSimpleName();
        }

        return new AsyncTaskResult<>(null, apiResult);
    }

    public VerifyActionIdTask(IWebIdMobileAppSdk sdkInstance) {
        this.sdkInstance = sdkInstance;
    }

    @Override
    protected void onPostExecute(AsyncTaskResult<VerifyActionIdResult> data) {
        if (iVerifyActionIdInternalOnPostExecuteCallback != null) {
            iVerifyActionIdInternalOnPostExecuteCallback.onPostExecute(data);
        }
    }

    public VerifyActionIdTask setOnPostExecuteCallback(IOnPostExecuteCallback<AsyncTaskResult<VerifyActionIdResult>> onPostExecuteCallback) {
        this.iVerifyActionIdInternalOnPostExecuteCallback = onPostExecuteCallback;
        return this;
    }
}