import { environment } from 'src/environments/environment'; import { v4 as uuidv4 } from 'uuid'; import { ResponseType } from '../enums/response-type.enum'; import { PollUserAnswers } from './poll-user-answers.model'; import { Choice } from './choice.model'; import { Comment } from './comment.model'; import { Configuration } from './configuration.model'; import { User } from './user.model'; export class Poll { constructor( public owner: User, public question: string, public description?: string, public slug: string = uuidv4(), public configuration: Configuration = new Configuration(), public comments: Comment[] = [], public choices: Choice[] = [], public answersByChoiceByParticipant: Map> = new Map< string, Map >(), public answers: PollUserAnswers[] = [] ) {} public getAdministrationUrl(): string { return `${environment.api.baseHref}/administration/polls/${this.slug}`; } public getParticipationUrl(): string { return `${environment.api.baseHref}/participation/polls/${this.slug}`; } public static adaptFromLocalJsonServer( item: Pick< Poll, | 'owner' | 'question' | 'description' | 'slug' | 'configuration' | 'comments' | 'choices' | 'answersByChoiceByParticipant' | 'answers' > ): Poll { const poll = new Poll( new User(item.owner.pseudo, item.owner.email, undefined), item.question, item.description, item.slug, item.configuration, item.comments .map( (c: Pick) => new Comment(c.author, c.content, new Date(c.dateCreated)) ) .sort(Comment.sortChronologically), item.choices.map((c: Pick) => { const choice = new Choice(c.label, c.imageUrl, new Map(c.participants)); choice.participants.forEach((value, key) => { choice.participants.set(key, new Set(value)); }); choice.updateCounts(); return choice; }) ); // handle answersByChoiceByParticipant for (const [pseudo, answersByChoice] of Object.entries(item.answersByChoiceByParticipant)) { if (!poll.answersByChoiceByParticipant.has(pseudo)) { poll.answersByChoiceByParticipant.set(pseudo, new Map()); } for (const [choiceLabel, answer] of Object.entries(answersByChoice)) { poll.answersByChoiceByParticipant.get(pseudo).set(choiceLabel, answer as ResponseType); } } // handle answers poll.answers = item.answers.map( (pollUserAnswers: Pick) => new PollUserAnswers(pollUserAnswers.pseudo, pollUserAnswers.token, pollUserAnswers.responsesByChoices) ); return poll; } }