import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { MessageSeverity } from '../enums/message-severity.enum'; import { ResponseType } from '../enums/response-type.enum'; import { Choice } from '../models/choice.model'; import { Poll } from '../models/poll.model'; import { User } from '../models/user.model'; import { ApiService } from './api.service'; import { MessageDisplayerService } from './message-displayer.service'; @Injectable({ providedIn: 'root', }) export class PollService { private _poll: BehaviorSubject = new BehaviorSubject(undefined); public readonly poll: Observable = this._poll.asObservable(); constructor(private apiService: ApiService, private messageDisplayerService: MessageDisplayerService) {} public updateCurrentPoll(poll: Poll): void { this._poll.next(poll); } public async getPollBySlug(slug: string): Promise { const poll: Poll | undefined = await this.apiService.getPollBySlug(slug); this.updateCurrentPoll(poll); } public async saveCurrentPoll(): Promise { const pollUrl: string = await this.apiService.createPoll(this._poll.getValue()); // TODO: Maybe handle the url to update currentPoll according to backend response if (pollUrl) { this.messageDisplayerService.display(MessageSeverity.SUCCESS, 'Le sondage a été enregistré.'); } else { this.messageDisplayerService.display( MessageSeverity.ERROR, 'Le sondage n’a été correctement enregistré, veuillez ré-essayer.' ); } } public saveParticipation(choice: Choice, user: User, response: ResponseType): void { const currentPoll = this._poll.getValue(); currentPoll.choices.find((c) => c.label === choice.label)?.updateParticipation(user.pseudo, response); this.updateCurrentPoll(currentPoll); this.apiService.createParticipation(currentPoll.slug, choice.label, user.pseudo, response); this.messageDisplayerService.display( MessageSeverity.SUCCESS, 'Votre participation au sondage a été enregistrée.' ); } public async deleteAllAnswers(): Promise { await this.apiService.deletePollAnswers(this._poll.getValue().slug); this.messageDisplayerService.display( MessageSeverity.SUCCESS, 'Les participations des votants à ce sondage ont été supprimées.' ); } public async addComment(comment: string): Promise { await this.apiService.createComment(this._poll.getValue().slug, comment); this.messageDisplayerService.display(MessageSeverity.SUCCESS, 'Votre commentaire a été enregistré.'); } public async deleteComments(): Promise { await this.apiService.deletePollComments(this._poll.getValue().slug); this.messageDisplayerService.display( MessageSeverity.SUCCESS, 'Les commentaires de ce sondage ont été supprimés.' ); } }