Passed
Push — master ( 1a6db4...d22713 )
by Muhammad Dyas
01:40
created

PollDialogCard.choice   A

Complexity

Conditions 1

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 23
rs 9.45
c 0
b 0
f 0
cc 1
1
import PollCard from './PollCard';
2
import {LocaleTimezone, PollState, Voter} from '../helpers/interfaces';
3
import {chat_v1 as chatV1} from '@googleapis/chat';
4
import {progressBarText} from '../helpers/vote';
5
6
export default class PollDialogCard extends PollCard {
7
  private readonly voter: Voter;
8
  private readonly userVotes: number[];
9
10
  constructor(state: PollState, timezone: LocaleTimezone, voter: Voter) {
11
    super(state, timezone);
12
    this.voter = voter;
13
    this.userVotes = this.getUserVotes();
14
  }
15
16
  getUserVotes(): number[] {
17
    if (this.state.votes === undefined) {
18
      return [];
19
    }
20
    const votes = [];
21
    const voter = this.voter;
22
    for (let i = 0; i < this.state.choices.length; i++) {
23
      if (this.state.votes[i] !== undefined && this.state.votes[i].findIndex((x) => x.uid === voter.uid) > -1) {
24
        votes.push(i);
25
      }
26
    }
27
    return votes;
28
  }
29
30
  sectionInfo(): chatV1.Schema$GoogleAppsCardV1Section {
31
    const votedCount = this.userVotes.length;
32
    const voteLimit = this.state.voteLimit || this.state.choices.length;
33
    const voteRemaining = voteLimit - votedCount;
34
    let warningMessage = '';
35
    if (voteRemaining === 0) {
36
      warningMessage = 'Vote limit reached. Your vote will be overwritten.';
37
    }
38
    return {
39
      widgets: [
40
        {
41
          'decoratedText': {
42
            'text': `You have voted: ${votedCount} out of ${voteLimit} (remaining: ${voteRemaining})`,
43
            'wrapText': true,
44
            'bottomLabel': warningMessage,
45
          },
46
        },
47
      ],
48
    };
49
  }
50
  choice(index: number, text: string, voteCount: number, totalVotes: number): chatV1.Schema$GoogleAppsCardV1Widget {
51
    const progressBar = progressBarText(voteCount, totalVotes);
52
53
    const voteSwitch: chatV1.Schema$GoogleAppsCardV1SwitchControl = {
54
      'controlType': 'SWITCH',
55
      'name': 'mySwitchControl',
56
      'value': 'myValue',
57
      'selected': this.userVotes.includes(index),
58
      'onChangeAction': {
59
        'function': 'switch_vote',
60
        'parameters': [
61
          {
62
            key: 'index',
63
            value: index.toString(10),
64
          },
65
        ],
66
      },
67
    };
68
    return {
69
      decoratedText: {
70
        'bottomLabel': `${progressBar} ${voteCount}`,
71
        'text': text,
72
        'switchControl': voteSwitch,
73
      },
74
    };
75
  }
76
}
77