package com.codeforgvl.trolleytrackerclient;

import android.support.v4.app.FragmentManager;

import org.joda.time.DateTime;
import org.joda.time.ReadableInstant;
import org.joda.time.base.AbstractPartial;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.codeforgvl.trolleytrackerclient.activities.MainActivity;


/**
 * Created by Adam on 12/30/2015.
 */
public class Utils {
    public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
        DateTime dt = lp.toDateTime(now);
        while (dt.isBefore(now)) {
            dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
        }
        return dt;
    }

    public static String getActiveFragmentName(FragmentManager m){
        int stackSize = m.getBackStackEntryCount();
        if(stackSize > 0) {
            return m.getBackStackEntryAt(stackSize - 1).getName();
        }
        else{
            return MainActivity.MAP_FRAGMENT_TAG;
        }
    }

    /**
     * Requests the fine location permission. If a rationale with an additional explanation should
     * be shown to the user, displays a dialog that triggers the request.
     */
    public static void requestPermission(AppCompatActivity activity, int requestId,
                                         String permission, boolean finishActivity) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
            // Display a dialog with rationale.
            Utils.RationaleDialog.newInstance(requestId, finishActivity)
                    .show(activity.getSupportFragmentManager(), "dialog");
        } else {
            // Location permission has not been granted yet, request it.
            ActivityCompat.requestPermissions(activity, new String[]{permission}, requestId);

        }
    }

    /**
     * A dialog that explains the use of the location permission and requests the necessary
     * permission.
     * <p>
     * The activity should implement
     * {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback}
     * to handle permit or denial of this permission request.
     */
    public static class RationaleDialog extends DialogFragment {

        private static final String ARGUMENT_PERMISSION_REQUEST_CODE = "requestCode";

        private static final String ARGUMENT_FINISH_ACTIVITY = "finish";

        private boolean mFinishActivity = false;

        /**
         * Creates a new instance of a dialog displaying the rationale for the use of the location
         * permission.
         * <p>
         * The permission is requested after clicking 'ok'.
         *
         * @param requestCode    Id of the request that is used to request the permission. It is
         *                       returned to the
         *                       {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback}.
         * @param finishActivity Whether the calling Activity should be finished if the dialog is
         *                       cancelled.
         */
        public static RationaleDialog newInstance(int requestCode, boolean finishActivity) {
            Bundle arguments = new Bundle();
            arguments.putInt(ARGUMENT_PERMISSION_REQUEST_CODE, requestCode);
            arguments.putBoolean(ARGUMENT_FINISH_ACTIVITY, finishActivity);
            RationaleDialog dialog = new RationaleDialog();
            dialog.setArguments(arguments);
            return dialog;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Bundle arguments = getArguments();
            final int requestCode = arguments.getInt(ARGUMENT_PERMISSION_REQUEST_CODE);
            mFinishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY);

            return new AlertDialog.Builder(getActivity())
                    .setMessage(R.string.permission_rationale_location)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // After click on Ok, request the permission.
                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    requestCode);
                            // Do not finish the Activity while requesting permission.
                            mFinishActivity = false;
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .create();
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            super.onDismiss(dialog);
            if (mFinishActivity) {
                Toast.makeText(getActivity(),
                        R.string.permission_required_toast,
                        Toast.LENGTH_SHORT)
                        .show();
                getActivity().finish();
            }
        }
    }
}

@@ -35,24 +35,53 @@
 kerclient;%0A%0A
+import android.app.Activity;%0A
 import andro
@@ -546,24 +546,130 @@
 get.Toast;%0A%0A
+import com.afollestad.materialdialogs.DialogAction;%0Aimport com.afollestad.materialdialogs.MaterialDialog;%0A
 import com.c
@@ -4215,21 +4215,24 @@
 urn new 
-Alert
+Material
 Dialog.B
@@ -4241,24 +4241,23 @@
 lder(get
-Activity
+Context
 ())%0A    
@@ -4277,18 +4277,15 @@
    .
-setMessage
+content
 (R.s
@@ -4346,82 +4346,172 @@
    .
-setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener
+positiveText(android.R.string.ok)%0A                    .negativeText(android.R.string.cancel)%0A                    .onPositive(new MaterialDialog.SingleButtonCallback
 () %7B
@@ -4593,35 +4593,43 @@
 ick(
-DialogInterface dialog, int
+MaterialDialog dialog, DialogAction
  whi
@@ -5119,106 +5119,14 @@
   %7D)
-%0A                    .setNegativeButton(android.R.string.cancel, null)%0A                    .create
+.build
 ();%0A
@@ -5259,20 +5259,89 @@
         
-if (
+Activity mActivity = getActivity();%0A            if (mActivity != null && 
 mFinishA
@@ -5382,27 +5382,25 @@
 akeText(
-get
+m
 Activity
 (),%0A    
@@ -5383,34 +5383,32 @@
 keText(mActivity
-()
 ,%0A              
@@ -5546,27 +5546,25 @@
         
-get
+m
 Activity
 ().finis
@@ -5555,18 +5555,16 @@
 Activity
-()
 .finish(

Fix #40, add null checks and fix styles on permission rationale dialog