class IntentImportInformationInteractor {

    @NonNull
    public Observable<UiIndicator<IntentImportResult>> process(@NonNull final Intent intent) {
        if (intent.hasExtra(INTENT_INFORMATION_SHOW)) {
            return Observable.just(UiIndicator.idle());
        } else {
            return intentImportProcessor.process(intent)
                    .flatMap(intentImportResult -> {
                        if (intentImportResult.getUri().toString().startsWith(ContentResolver.SCHEME_CONTENT)) {
                            return Maybe.just(intentImportResult);
                        } else {
                            final IntentImportResult intentImportResultReference = intentImportResult;
                            return permissionStatusChecker.isPermissionGranted(READ_PERMISSION)
                                    .subscribeOn(AndroidSchedulers.mainThread())
                                    .flatMapMaybe(isGranted -> {
                                        if (isGranted) {
                                            return Maybe.just(intentImportResult);
                                        } else {
                                            return permissionRequester.request(READ_PERMISSION)
                                                    .flatMapMaybe(permissionAuthorizationResponse -> {
                                                        if (permissionAuthorizationResponse.wasGranted()) {
                                                            return Maybe.just(intentImportResultReference);
                                                        } else {
                                                            permissionRequester.markRequestConsumed(READ_PERMISSION);
                                                            return Maybe.error(new PermissionsNotGrantedException("User failed to grant READ permission", READ_PERMISSION));
                                                        }
                                                    });
                                        }
                                    });
                        }
                    })
                    .doOnSuccess(ignored -> intent.putExtra(INTENT_INFORMATION_SHOW, true))
                    .toObservable()
                    .map(UiIndicator::success)
                    .startWith(UiIndicator.idle());
        }
    }

    @Inject public  IntentImportInformationInteractor(@NonNull IntentImportProcessor intentImportProcessor,
                                             @NonNull PermissionStatusChecker permissionStatusChecker,
                                             @NonNull ActivityPermissionsRequester<SmartReceiptsActivity> permissionRequester);

}