import {Injectable} from '@angular/core'; import {AngularFireDatabase, SnapshotAction} from '@angular/fire/compat/database'; import {Observable, Subject, Subscription} from 'rxjs'; import {Body} from '../auth/administration/bodies/body'; import {Session} from '../auth/edit/session'; import {Router} from '@angular/router'; @Injectable({ providedIn: 'root' }) export class SessionInBodyService { public readonly bodies: Observable[]>; public readonly sessions: Subject[]> = new Subject[]>(); private _currentPage: string | undefined; get currentPage(): string|undefined { return this._currentPage; } public readonly fullSessions: Observable[]>; private sessionsMap: Map[]> = new Map[]>(); private subscription: Subscription | undefined; constructor(private database: AngularFireDatabase, private router: Router) { const bodyRef = this.database.list('bodies'); this.bodies = bodyRef.snapshotChanges(); const sessionRef = this.database.list('sessions'); this.fullSessions = sessionRef.snapshotChanges(); this.subscription = this.fullSessions.subscribe(sessions => { this.sessionsMap = new Map[]>(); for (const session of sessions) { const payload = session.payload.val(); if (payload == null) { continue; } let sessionsPerBody = this.sessionsMap.get(payload.body); if (sessionsPerBody == null) { sessionsPerBody = []; this.sessionsMap.set(payload.body, sessionsPerBody); } sessionsPerBody.push(session); } this.changeBody(this.currentPage, undefined); }); } public changeBody(newBody: string | undefined, redirectUrl: string | undefined): void { if (newBody == null) { return; } this._currentPage = newBody; this.sessions.next(this.sessionsMap.get(newBody)); if (redirectUrl != null) { this.router.navigate([redirectUrl]); } } }