package me.id.webverifylib;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;

import me.id.webverifylib.exception.IDmeException;
import me.id.webverifylib.listener.IDmeAccessTokenManagerListener;
import me.id.webverifylib.networking.GetAccessTokenConnectionTask;

public class RedirectUriReceiverActivity extends Activity {
  private final IDmeAccessTokenManagerListener authCodeListener = new IDmeAccessTokenManagerListener() {
    @Override
    public void onSuccess(AuthToken authToken) {
      IDmeWebVerify.getInstance().notifySuccess(authToken);
      sendResult(RESULT_OK);
    }

    @Override
    public void onError(Throwable throwable) {
      IDmeWebVerify.getInstance().notifyFailure(throwable);
      sendResult(RESULT_CANCELED);
    }
  };

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    State currentState = IDmeWebVerify.getCurrentState();
    if (currentState == null) {
      throw new IDmeException("Current state cannot be null");
    }

    if (currentState == State.LOGOUT) {
      IDmeWebVerify.getInstance().notifyLogoutSuccess();
      sendResult(RESULT_OK);
      return;
    }

    String code = getIntent().getData().getQueryParameter(IDmeWebVerify.PARAM_CODE);
    if (code == null || code.isEmpty()) {
      IDmeWebVerify.getInstance().notifyFailure(new IDmeException("An error has occurred getting the auth token"));
      sendResult(RESULT_CANCELED);
    } else {
      new GetAccessTokenConnectionTask(IDmeWebVerify.getAccessTokenQuery(code), authCodeListener, currentState.getScope())
          .execute(IDmeWebVerify.getIdMeWebVerifyAccessTokenUri());
    }
  }

  private void sendResult(int resultCode) {
    setResult(resultCode);
    finish();
  }
}

@@ -971,24 +971,25 @@
 entState();%0A
+%0A
     if (curr
@@ -1018,14 +1018,50 @@
     
-throw 
+IDmeWebVerify.getInstance().notifyFailure(
 new 
@@ -1105,16 +1105,298 @@
 e null%22)
+);%0A      sendResult(RESULT_CANCELED);%0A      return;%0A    %7D%0A%0A    if (getIntent() == null %7C%7C getIntent().getData() == null) %7B%0A      IDmeWebVerify.getInstance().notifyFailure(new IDmeException(%22Null intent or invalid data was received%22));%0A      sendResult(RESULT_CANCELED);%0A      return
 ;%0A    %7D%0A

send error back instead of throwing if no intent is received