unoffical wafrn mirror
wafrn.net
atproto
social-network
activitypub
1import { Component, input, OnInit, Signal, inject } from '@angular/core'
2import { FormControl, UntypedFormGroup, Validators } from '@angular/forms'
3import { QuestionPoll } from '../../interfaces/questionPoll'
4import { LoginService } from '../../services/login.service'
5import { PostsService } from '../../services/posts.service'
6
7@Component({
8 selector: 'app-poll',
9 templateUrl: './poll.component.html',
10 styleUrls: ['./poll.component.scss'],
11 standalone: false
12})
13export class PollComponent implements OnInit {
14 protected loginService = inject(LoginService);
15 private postsService = inject(PostsService);
16
17 poll = input.required<QuestionPoll>()
18 total = 0
19 openPoll = false
20 form = new UntypedFormGroup({})
21 alreadyVoted = true
22
23 ngOnInit(): void {
24 this.openPoll = new Date().getTime() < this.poll().endDate.getTime()
25 this.poll().questionPollQuestions.forEach((elem) => {
26 this.total = this.total + elem.remoteReplies
27 })
28 this.alreadyVoted = this.poll().questionPollQuestions.some((question) => question.questionPollAnswers.length > 0)
29 if (this.poll().questionPollQuestions && this.poll().questionPollQuestions.length > 0 && this.poll().multiChoice) {
30 this.poll().questionPollQuestions.forEach((question) => {
31 this.form.addControl(
32 question.id.toString(),
33 new FormControl(
34 {
35 value: question.questionPollAnswers.length > 0,
36 disabled: this.alreadyVoted || !this.loginService.loggedIn.value || !this.openPoll
37 },
38 Validators.required
39 )
40 )
41 })
42 }
43 if (!this.poll().multiChoice) {
44 const existingReply = this.poll().questionPollQuestions.find((reply) => reply.questionPollAnswers.length > 0)
45 this.form.addControl(
46 'singleValue',
47 new FormControl(
48 {
49 value: existingReply ? existingReply.id : '',
50 disabled: this.alreadyVoted || !this.loginService.loggedIn.value || !this.openPoll
51 },
52 Validators.required
53 )
54 )
55 }
56 }
57
58 async vote() {
59 let votes: number[] = []
60 const formValue = this.form.value
61 if (this.poll().multiChoice) {
62 Object.keys(formValue).forEach((key) => {
63 if (formValue[key]) {
64 votes.push(parseInt(key))
65 }
66 })
67 } else {
68 votes.push(parseInt(formValue.singleValue))
69 }
70 const voteSuccess = await this.postsService.voteInPoll(this.poll().id, votes)
71 if (voteSuccess) {
72 this.alreadyVoted = true
73 }
74 }
75}