package com.p3.bewoplaner.page.common;

import com.p3.bewoplaner.R;
import com.p3.bewoplaner.utils.DialogHandler;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseIntArray;


/**
 * This class handles runtime permissions from activities.
 * <p>
 * Created by Rares on 29/08/16.
 */
public abstract class RuntimePermissionActivity extends AppCompatActivity {

    private SparseIntArray mErrorString;
    private PermissionGrantedListener mPermissionGrantedListener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mErrorString = new SparseIntArray();
    }

    /**
     * @param requestedPermissions      the permissions that we need to grant
     * @param stringId                  the id of the message that we show while requesting
     * @param requestCode               the request code for this permission request
     * @param permissionGrantedListener the listener which it's method will be called when
     *                                  permission is granted
     */
    public void requestAppPermissions(final String[] requestedPermissions,
                                      final int stringId,
                                      final int requestCode,
                                      @NonNull PermissionGrantedListener permissionGrantedListener) {
        mPermissionGrantedListener = permissionGrantedListener;
        mErrorString.put(requestCode, stringId);
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        boolean shouldShowRequestPermissionRationale = false;
        for (String permission : requestedPermissions) {
            permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
            shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale) {
                Dialog dialog = DialogHandler.createNoTitleDialog(this,
                        stringId,
                        true,
                        R.string.permission_grant,
                        (dialogInterface, i) -> requestPermissionCorrectly(requestedPermissions, requestCode));
                dialog.show();

            } else {
                requestPermissionCorrectly(requestedPermissions, requestCode);
            }
        } else {
            mPermissionGrantedListener.onPermissionsGranted(requestCode);
        }
    }

    protected void requestPermissionCorrectly(String[] requestedPermissions, int requestCode) {
        ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
    }

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

        if (mErrorString.size() == 0 || mErrorString.get(requestCode) == 0) {
            return;
        }

        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (int permission : grantResults) {
            permissionCheck = permissionCheck + permission;
        }
        if ((grantResults.length > 0) && permissionCheck == PackageManager.PERMISSION_GRANTED) {
            mPermissionGrantedListener.onPermissionsGranted(requestCode);
        } else {
            Dialog dialog = DialogHandler.createNoTitleDialog(this,
                    mErrorString.get(requestCode),
                    true,
                    R.string.permission_enable,
                    (dialogInterface, i) -> {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        startActivity(intent);
                    });
            dialog.show();
        }
    }

}
