60 lines
2.1 KiB
TypeScript
60 lines
2.1 KiB
TypeScript
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<SnapshotAction<Body>[]>;
|
|
public readonly sessions: Subject<SnapshotAction<Session>[]> = new Subject<SnapshotAction<Session>[]>();
|
|
|
|
private _currentPage: string | undefined;
|
|
get currentPage(): string|undefined {
|
|
return this._currentPage;
|
|
}
|
|
|
|
public readonly fullSessions: Observable<SnapshotAction<Session>[]>;
|
|
private sessionsMap: Map<string, SnapshotAction<Session>[]> = new Map<string, SnapshotAction<Session>[]>();
|
|
private subscription: Subscription | undefined;
|
|
|
|
constructor(private database: AngularFireDatabase,
|
|
private router: Router) {
|
|
const bodyRef = this.database.list<Body>('bodies');
|
|
this.bodies = bodyRef.snapshotChanges();
|
|
const sessionRef = this.database.list<Session>('sessions');
|
|
this.fullSessions = sessionRef.snapshotChanges();
|
|
this.subscription = this.fullSessions.subscribe(sessions => {
|
|
this.sessionsMap = new Map<string, SnapshotAction<Session>[]>();
|
|
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]);
|
|
}
|
|
}
|
|
}
|