package com.p3.bewoplaner.utils;


import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;

/**
 * Created by Vlad on 27/02/2017.
 */
public abstract class RuntimePermissionBaseFragment extends Fragment {

    protected static final int MY_STORAGE_PERMISSION = 1;

    /**
     * Request permission.
     */
    public void requestPermission(String permission, int permissionCode) {
        if (permissionGranted(permission)) {
            onPermissionGranted(permissionCode);
            return;
        }
        requestPermissions(new String[]{permission}, permissionCode);
    }

    /**
     * Check if already got the permission.
     */
    private boolean permissionGranted(String permission) {
        return getActivity() != null &&
                ContextCompat.checkSelfPermission(getActivity(), permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * Response for permission.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            onPermissionGranted(requestCode);
        } else {
            onPermissionDenied(requestCode);
        }
    }

    abstract public void onPermissionGranted(int permissionCode);

    abstract public void onPermissionDenied(int permissionCode);

}
