import * as i0 from '@angular/core';
import { InjectionToken, isDevMode, NgZone, Injectable, Inject, Optional, NgModule } from '@angular/core';
import * as i1 from '@rxap/config';
import { ConfigService } from '@rxap/config';
import { EMPTY, Observable, from, ReplaySubject } from 'rxjs';
import { shareReplay, map, switchMap, tap, mergeMapTo } from 'rxjs/operators';
import { ɵfirebaseAppFactory as _firebaseAppFactory, FIREBASE_OPTIONS, FIREBASE_APP_NAME } from '@angular/fire/compat';
import * as i1$1 from '@angular/fire/app-check';
import { onTokenChanged, getToken, setTokenAutoRefreshEnabled } from '@angular/fire/app-check';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { coerceArray } from '@rxap/utilities';
import * as i1$2 from '@angular/fire/compat/messaging';
import { AngularFireMessaging, VAPID_KEY, SERVICE_WORKER } from '@angular/fire/compat/messaging';
import { FirebaseApp } from '@angular/fire/app';
import { USE_EMULATOR as USE_EMULATOR$2, TENANT_ID, LANGUAGE_CODE, USE_DEVICE_LANGUAGE, PERSISTENCE, SETTINGS as SETTINGS$1 } from '@angular/fire/compat/auth';
import { INSTRUMENTATION_ENABLED, DATA_COLLECTION_ENABLED } from '@angular/fire/compat/performance';
import * as i1$3 from '@angular/fire/compat/storage';
import { BUCKET, MAX_UPLOAD_RETRY_TIME, MAX_OPERATION_RETRY_TIME } from '@angular/fire/compat/storage';
import { COLLECTION_ENABLED, APP_NAME } from '@angular/fire/compat/analytics';
import { ENABLE_PERSISTENCE, PERSISTENCE_SETTINGS, SETTINGS, USE_EMULATOR } from '@angular/fire/compat/firestore';
import { REGION, ORIGIN, USE_EMULATOR as USE_EMULATOR$1 } from '@angular/fire/compat/functions';

const RXAP_REQUEST_CLOUD_MESSAGING_TOKEN = new InjectionToken('rxap/firebase/request-cloud-messaging-token');
const APP_CHECK_ENABLED = new InjectionToken('rxap/firebase/app-check-enabled');
const APP_CHECK_SITE_KEY = new InjectionToken('rxap/firebase/app-check-site-key');
const APP_CHECK_IS_TOKEN_AUTO_REFRESH_ENABLED = new InjectionToken('rxap/firebase/app-check-is-token-auto-refresh-enabled');
const FIREBASE_APP_CHECK_HTTP_INTERCEPTOR_URL_PATTERN = new InjectionToken('firebase-app-check-http-interceptor-url-pattern');

class AppCheckService {
    constructor(options, nameOrConfig, zone, config, enabled, siteKey, isTokenAutoRefreshEnabled) {
        this.config = config;
        this.enabled = enabled;
        this.onTokenChanged$ = EMPTY;
        this._appCheck = null;
        if (this.enabled) {
            if (siteKey) {
                const app = _firebaseAppFactory(options, zone, nameOrConfig);
                const appCheck = this._appCheck = app.appCheck();
                appCheck.activate(siteKey, isTokenAutoRefreshEnabled ?? undefined);
                this.onTokenChanged$ = (new Observable(subscriber => {
                    onTokenChanged(appCheck, tokenResult => subscriber.next(tokenResult), error => subscriber.error(error), () => subscriber.complete());
                })).pipe(shareReplay(1));
            }
            else {
                if (isDevMode()) {
                    console.error('The app check site key is not provided');
                }
            }
        }
        else {
            if (isDevMode()) {
                console.warn('App check is disabled');
            }
        }
    }
    getToken(forceRefresh) {
        if (this._appCheck) {
            return getToken(this._appCheck, forceRefresh).then(result => result.token) ??
                Promise.reject(new Error('firebase app check is not initialized'));
        }
        return Promise.reject(new Error('firebase app check is not initialized'));
    }
    setTokenAutoRefreshEnabled(isTokenAutoRefreshEnabled) {
        if (this._appCheck) {
            setTokenAutoRefreshEnabled(this._appCheck, isTokenAutoRefreshEnabled);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: AppCheckService, deps: [{ token: FIREBASE_OPTIONS }, { token: FIREBASE_APP_NAME, optional: true }, { token: NgZone }, { token: i1.ConfigService }, { token: APP_CHECK_ENABLED, optional: true }, { token: APP_CHECK_SITE_KEY, optional: true }, { token: APP_CHECK_IS_TOKEN_AUTO_REFRESH_ENABLED, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: AppCheckService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: AppCheckService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: undefined, decorators: [{
                    type: Inject,
                    args: [FIREBASE_OPTIONS]
                }] }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [FIREBASE_APP_NAME]
                }] }, { type: i0.NgZone, decorators: [{
                    type: Inject,
                    args: [NgZone]
                }] }, { type: i1.ConfigService }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [APP_CHECK_ENABLED]
                }] }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [APP_CHECK_SITE_KEY]
                }] }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [APP_CHECK_IS_TOKEN_AUTO_REFRESH_ENABLED]
                }] }] });
class RxapAngularFireAppCheckModule {
    constructor(appCheck) {
        this.appCheck = appCheck;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireAppCheckModule, deps: [{ token: AppCheckService }], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireAppCheckModule }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireAppCheckModule, providers: [AppCheckService] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireAppCheckModule, decorators: [{
            type: NgModule,
            args: [{
                    providers: [AppCheckService],
                }]
        }], ctorParameters: () => [{ type: AppCheckService, decorators: [{
                    type: Inject,
                    args: [AppCheckService]
                }] }] });

class FirebaseAppCheckHttpInterceptor {
    constructor(appCheck, urlPattern, enabled) {
        this.appCheck = appCheck;
        this.enabled = enabled;
        this.urlPattern = [];
        this.urlPattern = coerceArray(urlPattern);
    }
    intercept(req, next) {
        if (this.enabled && this.isMatch(req)) {
            return from(getToken(this.appCheck)).pipe(map(response => response.token), switchMap(token => next.handle(req.clone({
                setHeaders: {
                    'X-Firebase-AppCheck': token,
                },
            }))));
        }
        return next.handle(req);
    }
    isMatch(req) {
        return this.urlPattern.some(pattern => req.url.match(pattern));
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: FirebaseAppCheckHttpInterceptor, deps: [{ token: i1$1.AppCheck }, { token: FIREBASE_APP_CHECK_HTTP_INTERCEPTOR_URL_PATTERN }, { token: APP_CHECK_ENABLED, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: FirebaseAppCheckHttpInterceptor }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: FirebaseAppCheckHttpInterceptor, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i1$1.AppCheck }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [FIREBASE_APP_CHECK_HTTP_INTERCEPTOR_URL_PATTERN]
                }] }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [APP_CHECK_ENABLED]
                }] }] });
const FIREBASE_APP_CHECK_HTTP_INTERCEPTOR = {
    provide: HTTP_INTERCEPTORS,
    useClass: FirebaseAppCheckHttpInterceptor,
    multi: true,
};

class RxapFirebaseMessagingService {
    constructor(messaging, requestPermissionImminently = false) {
        this.messaging = messaging;
        this.requestPermissionImminently = requestPermissionImminently;
        this.token$ = new ReplaySubject(1);
        this.messaging.messages
            .pipe(tap((message) => this.showNotification(message.notification.title, message.notification.body)))
            .subscribe();
        if (this.requestPermissionImminently) {
            this.requestPermission();
        }
    }
    requestPermission() {
        console.log('request notification permission');
        this.messaging.requestPermission
            .pipe(mergeMapTo(this.messaging.tokenChanges))
            .subscribe((token) => {
            console.info('cloud messaging permission is granted');
            this.token$.next(token);
        }, () => console.error('cloud messaging permission is denied'));
    }
    showNotification(title, body) {
        // Let's check if the browser supports notifications
        if (!('Notification' in window)) {
            alert('This browser does not support desktop notification');
        }
        // Let's check whether notification permissions have already been granted
        else if (Notification.permission === 'granted') {
            // If it's okay let's create a notification
            new Notification(title, { body });
        }
        else {
            console.warn('Notification permission is not granted');
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapFirebaseMessagingService, deps: [{ token: AngularFireMessaging }, { token: RXAP_REQUEST_CLOUD_MESSAGING_TOKEN, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapFirebaseMessagingService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapFirebaseMessagingService, decorators: [{
            type: Injectable,
            args: [{ providedIn: 'root' }]
        }], ctorParameters: () => [{ type: i1$2.AngularFireMessaging, decorators: [{
                    type: Inject,
                    args: [AngularFireMessaging]
                }] }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [RXAP_REQUEST_CLOUD_MESSAGING_TOKEN]
                }] }] });

function FirebaseOptionsTokenFactory(configService) {
    return configService.get('firebase.options');
}
function FirebaseNameOrConfigTokenFactory(configService) {
    return configService.get('firebase.name', null);
}
function EnablePersistenceTokenFactory(configService) {
    return configService.get('firebase.firestore.enablePersistence', false);
}
function PersistenceSettingsTokenFactory(configService) {
    return configService.get('firebase.firestore.persistenceSettings', null);
}
function FirestoreSettingsTokenFactory(configService) {
    return configService.get('firebase.firestore.settings', null);
}
function FunctionsRegionFactory(configService) {
    return configService.get('firebase.functions.region', configService.get('firebase.region', null));
}
function FunctionsOriginFactory(configService) {
    return configService.get('firebase.functions.origin', configService.get('firebase.origin', null));
}
function FunctionsNewOriginBehaviorFactory(configService) {
    return configService.get('firebase.functions.newOriginBehavior');
}
function InstrumentationEnabledFactory(configService) {
    return configService.get('firebase.performance.instrumentationEnabled');
}
function DataCollectionEnabledFactory(configService) {
    return configService.get('firebase.performance.dataCollectionEnabled');
}
function VapidKeyFactory(configService) {
    return configService.get('firebase.messaging.vapid', configService.get('firebase.vapid'));
}
function AnalyticsEnabledFactory(configService) {
    return configService.get('firebase.analytics.enabled', null);
}
function GetAnalyticsAppName(config) {
    return config.get('appName');
}
function UseFirestoreEmulatorFactory(configService) {
    return configService.get('firebase.emulator.firestore', null);
}
function UseFunctionsEmulatorFactory(configService) {
    return configService.get('firebase.emulator.functions', null);
}
function UseAuthEmulatorFactory(configService) {
    return configService.get('firebase.emulator.auth', null);
}
function AuthTenantIdFactory(configService) {
    return configService.get('firebase.auth.tenantId', null);
}
function AuthLanguageCodeFactory(configService) {
    return configService.get('firebase.auth.languageCode', null);
}
function AuthUseDeviceLanguageFactory(configService) {
    return configService.get('firebase.auth.useDeviceLanguage', null);
}
function AuthPersistenceFactory(configService) {
    return configService.get('firebase.auth.persistence', null);
}
function AuthSettingsFactory(configService) {
    return configService.get('firebase.auth.settings', null);
}
function AppCheckEnabledFactory(configService) {
    return configService.get('firebase.appCheck.enabled', null);
}
function AppCheckSiteKeyFactory(configService) {
    return configService.get('firebase.appCheck.siteKey', null);
}
function AppIsTokenAutoRefreshEnabledFactory(configService) {
    return configService.get('firebase.appCheck.isTokenAutoRefreshEnabled', null);
}
function StorageBucketFactory(configService) {
    return configService.get('firebase.storage.bucket', configService.get('firebase.storageBucket', null));
}
function StorageMaxUploadRetryTimeFactory(configService) {
    return configService.get('firebase.storage.maxUploadRetryTime', null);
}
function StorageMaxOperationRetryTimeFactory(configService) {
    return configService.get('firebase.storage.maxOperationRetryTime', null);
}
function ServiceWorkerFactory() {
    return (typeof navigator !== 'undefined' && navigator.serviceWorker?.getRegistration()) ?? undefined;
}
const FIREBASE_APP_PROVIDERS = [
    {
        provide: FIREBASE_OPTIONS,
        useFactory: FirebaseOptionsTokenFactory,
        deps: [ConfigService],
    },
    {
        provide: FIREBASE_APP_NAME,
        useFactory: FirebaseNameOrConfigTokenFactory,
        deps: [ConfigService],
    },
    {
        provide: FirebaseApp,
        useFactory: _firebaseAppFactory,
        deps: [
            FIREBASE_OPTIONS,
            NgZone,
            [new Optional(), FIREBASE_APP_NAME],
        ],
    },
];
const FIREBASE_FIRESTORE_PROVIDERS = [
    {
        provide: ENABLE_PERSISTENCE,
        useFactory: EnablePersistenceTokenFactory,
        deps: [ConfigService],
    },
    {
        provide: PERSISTENCE_SETTINGS,
        useFactory: PersistenceSettingsTokenFactory,
        deps: [ConfigService],
    },
    {
        provide: SETTINGS,
        useFactory: FirestoreSettingsTokenFactory,
        deps: [ConfigService],
    },
    {
        provide: USE_EMULATOR,
        useFactory: UseFirestoreEmulatorFactory,
        deps: [ConfigService],
    },
];
const FIREBASE_FUNCTIONS_PROVIDERS = [
    {
        provide: REGION,
        useFactory: FunctionsRegionFactory,
        deps: [ConfigService],
    },
    {
        provide: ORIGIN,
        useFactory: FunctionsOriginFactory,
        deps: [ConfigService],
    },
    {
        provide: USE_EMULATOR$1,
        useFactory: UseFunctionsEmulatorFactory,
        deps: [ConfigService],
    },
];
const FIREBASE_MESSAGING_PROVIDERS = [
    {
        provide: VAPID_KEY,
        useFactory: VapidKeyFactory,
        deps: [ConfigService],
    },
    {
        provide: SERVICE_WORKER,
        useFactory: ServiceWorkerFactory,
        deps: [],
    },
];
const FIREBASE_PERFORMANCE_PROVIDERS = [
    {
        provide: INSTRUMENTATION_ENABLED,
        useFactory: InstrumentationEnabledFactory,
        deps: [ConfigService],
    },
    {
        provide: DATA_COLLECTION_ENABLED,
        useFactory: DataCollectionEnabledFactory,
        deps: [ConfigService],
    },
];
const FIREBASE_ANALYTICS_PROVIDERS = [
    {
        provide: COLLECTION_ENABLED,
        useFactory: AnalyticsEnabledFactory,
        deps: [ConfigService],
    },
    {
        provide: APP_NAME,
        useFactory: GetAnalyticsAppName,
        deps: [ConfigService],
    },
];
const FIREBASE_AUTH_PROVIDERS = [
    {
        provide: USE_EMULATOR$2,
        useFactory: UseAuthEmulatorFactory,
        deps: [ConfigService],
    },
    {
        provide: TENANT_ID,
        useFactory: AuthTenantIdFactory,
        deps: [ConfigService],
    },
    {
        provide: LANGUAGE_CODE,
        useFactory: AuthLanguageCodeFactory,
        deps: [ConfigService],
    },
    {
        provide: USE_DEVICE_LANGUAGE,
        useFactory: AuthUseDeviceLanguageFactory,
        deps: [ConfigService],
    },
    {
        provide: PERSISTENCE,
        useFactory: AuthPersistenceFactory,
        deps: [ConfigService],
    },
    {
        provide: SETTINGS$1,
        useFactory: AuthSettingsFactory,
        deps: [ConfigService],
    },
];
const FIREBASE_APP_CHECK_PROVIDERS = [
    {
        provide: APP_CHECK_ENABLED,
        useFactory: AppCheckEnabledFactory,
        deps: [ConfigService],
    },
    {
        provide: APP_CHECK_IS_TOKEN_AUTO_REFRESH_ENABLED,
        useFactory: AppIsTokenAutoRefreshEnabledFactory,
        deps: [ConfigService],
    },
    {
        provide: APP_CHECK_SITE_KEY,
        useFactory: AppCheckSiteKeyFactory,
        deps: [ConfigService],
    },
    AppCheckService,
];
const FIREBASE_STORAGE_PROVIDERS = [
    {
        provide: BUCKET,
        useFactory: StorageBucketFactory,
        deps: [ConfigService],
    },
    {
        provide: MAX_UPLOAD_RETRY_TIME,
        useFactory: StorageMaxUploadRetryTimeFactory,
        deps: [ConfigService],
    },
    {
        provide: MAX_OPERATION_RETRY_TIME,
        useFactory: StorageMaxOperationRetryTimeFactory,
        deps: [ConfigService],
    },
];
const FIREBASE_PROVIDERS = [
    FIREBASE_APP_PROVIDERS,
    FIREBASE_FIRESTORE_PROVIDERS,
    FIREBASE_FUNCTIONS_PROVIDERS,
    FIREBASE_MESSAGING_PROVIDERS,
    FIREBASE_PERFORMANCE_PROVIDERS,
    FIREBASE_ANALYTICS_PROVIDERS,
    FIREBASE_AUTH_PROVIDERS,
    FIREBASE_APP_CHECK_PROVIDERS,
    FIREBASE_STORAGE_PROVIDERS,
];

const USE_STORAGE_EMULATOR = new InjectionToken('rxap/firebase/use-storage-emulator');
class RxapAngularFireStorageModule {
    constructor(storage, useEmulator) {
        this.storage = storage;
        if (useEmulator) {
            this.storage.storage.useEmulator(...useEmulator);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireStorageModule, deps: [{ token: i1$3.AngularFireStorage }, { token: USE_STORAGE_EMULATOR, optional: true }], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireStorageModule }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireStorageModule }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.0.6", ngImport: i0, type: RxapAngularFireStorageModule, decorators: [{
            type: NgModule,
            args: [{}]
        }], ctorParameters: () => [{ type: i1$3.AngularFireStorage }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [USE_STORAGE_EMULATOR]
                }] }] });

// region 
// endregion

/**
 * Generated bundle index. Do not edit.
 */

export { APP_CHECK_ENABLED, APP_CHECK_IS_TOKEN_AUTO_REFRESH_ENABLED, APP_CHECK_SITE_KEY, AnalyticsEnabledFactory, AppCheckEnabledFactory, AppCheckService, AppCheckSiteKeyFactory, AppIsTokenAutoRefreshEnabledFactory, AuthLanguageCodeFactory, AuthPersistenceFactory, AuthSettingsFactory, AuthTenantIdFactory, AuthUseDeviceLanguageFactory, DataCollectionEnabledFactory, EnablePersistenceTokenFactory, FIREBASE_ANALYTICS_PROVIDERS, FIREBASE_APP_CHECK_HTTP_INTERCEPTOR, FIREBASE_APP_CHECK_HTTP_INTERCEPTOR_URL_PATTERN, FIREBASE_APP_CHECK_PROVIDERS, FIREBASE_APP_PROVIDERS, FIREBASE_AUTH_PROVIDERS, FIREBASE_FIRESTORE_PROVIDERS, FIREBASE_FUNCTIONS_PROVIDERS, FIREBASE_MESSAGING_PROVIDERS, FIREBASE_PERFORMANCE_PROVIDERS, FIREBASE_PROVIDERS, FIREBASE_STORAGE_PROVIDERS, FirebaseAppCheckHttpInterceptor, FirebaseNameOrConfigTokenFactory, FirebaseOptionsTokenFactory, FirestoreSettingsTokenFactory, FunctionsNewOriginBehaviorFactory, FunctionsOriginFactory, FunctionsRegionFactory, GetAnalyticsAppName, InstrumentationEnabledFactory, PersistenceSettingsTokenFactory, RXAP_REQUEST_CLOUD_MESSAGING_TOKEN, RxapAngularFireAppCheckModule, RxapAngularFireStorageModule, RxapFirebaseMessagingService, ServiceWorkerFactory, StorageBucketFactory, StorageMaxOperationRetryTimeFactory, StorageMaxUploadRetryTimeFactory, USE_STORAGE_EMULATOR, UseAuthEmulatorFactory, UseFirestoreEmulatorFactory, UseFunctionsEmulatorFactory, VapidKeyFactory };
//# sourceMappingURL=rxap-firebase.mjs.map
