package org.opendatakit.activities;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v13.app.ActivityCompat;
import android.support.v13.app.FragmentCompat;
import android.widget.Toast;

import org.opendatakit.androidcommon.R;
import org.opendatakit.consts.IntentConsts;
import org.opendatakit.consts.RequestCodeConsts;
import org.opendatakit.utilities.RuntimePermissionUtils;


public abstract class BaseLauncherActivity extends BaseActivity implements FragmentCompat.OnRequestPermissionsResultCallback {
  protected static final int REQUIRED_PERMISSIONS_REQ_CODE = 0;

  protected static final String[] REQUIRED_PERMISSIONS = new String[] {
      Manifest.permission.READ_EXTERNAL_STORAGE,
      Manifest.permission.WRITE_EXTERNAL_STORAGE
  };

  protected Bundle savedInstanceState;

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

    this.savedInstanceState = savedInstanceState;

    if (!RuntimePermissionUtils.checkPackageAllPermission(
        this, IntentConsts.Services.PACKAGE_NAME, REQUIRED_PERMISSIONS)) {
      Intent launchIntent = new Intent();
      launchIntent.setComponent(
          new ComponentName(IntentConsts.Services.PACKAGE_NAME, IntentConsts.Services.MAIN_ACTIVITY));
      launchIntent.setAction(Intent.ACTION_VIEW);
      launchIntent.putExtra(IntentConsts.INTENT_KEY_PERMISSION_ONLY, true);

      startActivityForResult(launchIntent, RequestCodeConsts.RequestCodes.LAUNCH_MAIN_ACTIVITY);
    }

    if (!RuntimePermissionUtils.checkSelfAnyPermission(this, REQUIRED_PERMISSIONS)) {
      ActivityCompat.requestPermissions(
          this, REQUIRED_PERMISSIONS, REQUIRED_PERMISSIONS_REQ_CODE);
    } else {
      onCreateWithPermission(savedInstanceState);
    }
  }

  protected abstract void onCreateWithPermission(Bundle savedInstanceState);

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode != REQUIRED_PERMISSIONS_REQ_CODE) {
      return;
    }

    AlertDialog.Builder builder =
        RuntimePermissionUtils.createPermissionRationaleDialog(this, requestCode, permissions);

    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      onCreateWithPermission(savedInstanceState);
    } else {
      if (RuntimePermissionUtils.shouldShowAnyPermissionRationale(this, permissions)) {
        builder
            .setMessage(R.string.required_permission_rationale)
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                finish();
              }
            })
            .show();
      } else {
        Toast
            .makeText(this, R.string.required_permission_perm_denied, Toast.LENGTH_LONG)
            .show();
        finish();
      }
    }
  }

  @Override
  protected void onResume() {
    // this is in onResume instead of onActivityResult because onResume is triggered first
    if (!RuntimePermissionUtils.checkPackageAllPermission(
        this, IntentConsts.Services.PACKAGE_NAME, REQUIRED_PERMISSIONS)) {
      Toast
          .makeText(this, R.string.required_permission_perm_denied_services, Toast.LENGTH_LONG)
          .show();
      finish();
    }

    super.onResume();
  }
}

@@ -55,16 +55,45 @@
 nifest;%0A
+import android.app.Activity;%0A
 import a
@@ -387,55 +387,8 @@
 at;%0A
-import android.support.v13.app.FragmentCompat;%0A
 impo
@@ -684,16 +684,16 @@
 nts 
-Fragment
+Activity
 Comp
@@ -1172,16 +1172,161 @@
 State;%0A%0A
+    // 1. check if Services has the right permissions%0A    //      if not, launch Services%0A    // 2. check if this app has the right permissions%0A%0A
     if (
@@ -1354,34 +1354,34 @@
 ls.checkPackageA
-ll
+ny
 Permission(%0A    
@@ -1854,26 +1854,34 @@
 VITY);%0A    %7D
-%0A%0A
+ else %7B%0A  
     if (!Run
@@ -1960,16 +1960,18 @@
 %7B%0A      
+  
 Activity
@@ -2003,24 +2003,26 @@
 (%0A          
+ 
+ 
 this, REQUIR
@@ -2069,24 +2069,26 @@
 _CODE);%0A    
+  
 %7D else %7B%0A   
@@ -2082,32 +2082,34 @@
  %7D else %7B%0A      
+ 
+ 
 onCreateWithPerm
@@ -2132,24 +2132,32 @@
 anceState);%0A
+      %7D%0A
     %7D%0A  %7D%0A%0A 
@@ -3479,109 +3479,372 @@
 d on
-Resume() %7B%0A    // this is in onResume instead of onActivityResult because onResume is triggered first
+ActivityResult(int requestCode, int resultCode, Intent data) %7B%0A    super.onActivityResult(requestCode, resultCode, data);%0A%0A    if(requestCode != RequestCodeConsts.RequestCodes.LAUNCH_MAIN_ACTIVITY) %7B%0A      return;%0A    %7D%0A%0A    if (resultCode != Activity.RESULT_OK) %7B%0A      System.exit(0); // cannot properly shutdown without Services having proper permissions%0A    %7D%0A
 %0A   
@@ -3881,18 +3881,15 @@
 heck
-PackageAll
+SelfAny
 Perm
@@ -3899,255 +3899,218 @@
 ion(
-%0A        this, IntentConsts.Services.PACKAGE_NAME, REQUIRED_PERMISSIONS)) %7B%0A      Toast%0A          .makeText(this, R.string.required_permission_perm_denied_services, Toast.LENGTH_LONG)%0A          .show();%0A      finish();%0A    %7D%0A%0A    super.onResume();
+this, REQUIRED_PERMISSIONS)) %7B%0A      ActivityCompat.requestPermissions(%0A          this, REQUIRED_PERMISSIONS, REQUIRED_PERMISSIONS_REQ_CODE);%0A    %7D else %7B%0A      onCreateWithPermission(savedInstanceState);%0A    %7D
 %0A  %7D

fix crash when Services has insufficient permissions