|
|
@@ -1,5 +1,6 @@
|
|
1
|
1
|
package io.zipcoder.tc_spring_poll_application.controller;
|
|
2
|
2
|
|
|
|
3
|
+import dtos.OptionCount;
|
|
3
|
4
|
import dtos.VoteResult;
|
|
4
|
5
|
import io.zipcoder.tc_spring_poll_application.domain.Vote;
|
|
5
|
6
|
import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
|
|
|
@@ -11,6 +12,8 @@ import org.springframework.web.bind.annotation.RequestParam;
|
|
11
|
12
|
import org.springframework.web.bind.annotation.RestController;
|
|
12
|
13
|
|
|
13
|
14
|
import javax.inject.Inject;
|
|
|
15
|
+import java.util.HashMap;
|
|
|
16
|
+import java.util.Map;
|
|
14
|
17
|
|
|
15
|
18
|
@RestController
|
|
16
|
19
|
public class ComputeResultController {
|
|
|
@@ -19,12 +22,28 @@ public class ComputeResultController {
|
|
19
|
22
|
private VoteRepository voteRepository;
|
|
20
|
23
|
|
|
21
|
24
|
@RequestMapping(value = "/computeresult", method = RequestMethod.GET)
|
|
22
|
|
- public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
|
|
|
25
|
+ public ResponseEntity<VoteResult> computeResult(@RequestParam Long pollId) {
|
|
23
|
26
|
VoteResult voteResult = new VoteResult();
|
|
24
|
27
|
Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
|
|
25
|
|
-
|
|
26
|
|
- //TODO: Implement algorithm to count votes
|
|
|
28
|
+ countVotes(voteResult, allVotes);
|
|
27
|
29
|
return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
|
|
28
|
30
|
}
|
|
29
|
31
|
|
|
|
32
|
+ private void countVotes(VoteResult voteResult, Iterable<Vote> allVotes) {
|
|
|
33
|
+ int totalVotes = 0;
|
|
|
34
|
+ Map<Long, OptionCount> map = new HashMap<>();
|
|
|
35
|
+ for(Vote v : allVotes) {
|
|
|
36
|
+ totalVotes ++;
|
|
|
37
|
+ OptionCount optionCount = map.get(v.getOption().getId());
|
|
|
38
|
+ if(optionCount == null) {
|
|
|
39
|
+ optionCount = new OptionCount();
|
|
|
40
|
+ optionCount.setOptionId(v.getOption().getId());
|
|
|
41
|
+ map.put(v.getOption().getId(), optionCount);
|
|
|
42
|
+ }
|
|
|
43
|
+ optionCount.setCount(optionCount.getCount()+1);
|
|
|
44
|
+ }
|
|
|
45
|
+ voteResult.setTotalVotes(totalVotes);
|
|
|
46
|
+ voteResult.setResults((map.values()));
|
|
|
47
|
+ }
|
|
|
48
|
+
|
|
30
|
49
|
}
|