package com.helpshift.react.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.helpshift.react.utils.InstallUtils;
import com.helpshift.core.HSContext;

/**
 * Delegate activity for proxying notifications clicked in app killed state.
 */
public class ReactNativeDelegateActivity extends Activity {


  private static final String TAG = "Helpshft_DelgteActvty";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {

      // Init Helpshift with cached creds.
      // React apps might not call install on application start since they prefer to call install in React's first
      // activity
      if (!InstallUtils.installWithCachedValues(getApplicationContext())) {
        finish();
        return;
      }

      // Synchronously wait for the install call to finish else we have a feature to start the default activity of the app
      // if install is not finished before starting the Helpshift's activity.
      HSContext.getInstance().getHsThreadingService().awaitForSyncExecution();

      // Get the actual intent to be fired to Helpshift.
      Intent intent = getIntent();
      PendingIntent pendingIntent = (PendingIntent) intent.getParcelableExtra("delegateIntent");
      if (pendingIntent != null) {
        try {
          pendingIntent.send();
        }
        catch (PendingIntent.CanceledException e) {
          Log.e(TAG, "Error in sending pending intent : " + e);
        }
      }
    }
    finally {
      // Finish the current activity
      finish();
    }
  }
}
