|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+package io.zipcoder.tc_spring_poll_application.controller;
|
|
|
2
|
+
|
|
|
3
|
+import dtos.OptionCount;
|
|
|
4
|
+import dtos.VoteResult;
|
|
|
5
|
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
|
|
|
6
|
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
|
|
|
7
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
8
|
+import org.springframework.http.HttpStatus;
|
|
|
9
|
+import org.springframework.http.ResponseEntity;
|
|
|
10
|
+import org.springframework.web.bind.annotation.RequestMapping;
|
|
|
11
|
+import org.springframework.web.bind.annotation.RequestMethod;
|
|
|
12
|
+import org.springframework.web.bind.annotation.RequestParam;
|
|
|
13
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
14
|
+
|
|
|
15
|
+import java.util.HashMap;
|
|
|
16
|
+import java.util.Map;
|
|
|
17
|
+
|
|
|
18
|
+@RestController
|
|
|
19
|
+public class ComputeResultController {
|
|
|
20
|
+
|
|
|
21
|
+ private VoteRepository voteRepository;
|
|
|
22
|
+
|
|
|
23
|
+ @Autowired
|
|
|
24
|
+ public ComputeResultController(VoteRepository voteRepository){
|
|
|
25
|
+ this.voteRepository = voteRepository;
|
|
|
26
|
+ }
|
|
|
27
|
+
|
|
|
28
|
+ @RequestMapping(value = "/computeresult", method = RequestMethod.GET)
|
|
|
29
|
+ public ResponseEntity<?> computeResult(@RequestParam Long pollId){ //requestparam annotation instructs SPring to retrieve the pollId value from a HTTP query
|
|
|
30
|
+ VoteResult voteResult = new VoteResult();
|
|
|
31
|
+ Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
|
|
|
32
|
+
|
|
|
33
|
+ int totalVotes = 0;
|
|
|
34
|
+ Map<Long, OptionCount> tempMap = new HashMap<>();
|
|
|
35
|
+ for(Vote v : allVotes) {
|
|
|
36
|
+ totalVotes ++;
|
|
|
37
|
+ // Get the OptionCount corresponding to this Option
|
|
|
38
|
+ OptionCount optionCount = tempMap.get(v.getOption().getId());
|
|
|
39
|
+ if(optionCount == null) {
|
|
|
40
|
+ optionCount = new OptionCount();
|
|
|
41
|
+ optionCount.setOptionId(v.getOption().getId());
|
|
|
42
|
+ tempMap.put(v.getOption().getId(), optionCount);
|
|
|
43
|
+ }
|
|
|
44
|
+ optionCount.setCount(optionCount.getCount()+1);
|
|
|
45
|
+ }
|
|
|
46
|
+ voteResult.setTotalVotes(totalVotes);
|
|
|
47
|
+ voteResult.setResults(tempMap.values());
|
|
|
48
|
+
|
|
|
49
|
+ return new ResponseEntity<>(voteResult, HttpStatus.OK); //computes results sent to client using new response entity
|
|
|
50
|
+ }
|
|
|
51
|
+}
|