-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathFlashCardServiceImpl.java
81 lines (68 loc) · 2.17 KB
/
FlashCardServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.teamtreehouse.flashy.services;
import com.teamtreehouse.flashy.domain.FlashCard;
import com.teamtreehouse.flashy.repositories.FlashCardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static java.util.stream.Collectors.toList;
@Service
public class FlashCardServiceImpl implements FlashCardService {
private FlashCardRepository flashCardRepository;
@Autowired
public void setFlashCardRepository(FlashCardRepository flashCardRepository) {
this.flashCardRepository = flashCardRepository;
}
@Override
public Long getCurrentCount() {
return flashCardRepository.count();
}
@Override
public FlashCard getFlashCardById(Long id) {
return flashCardRepository.findOne(id);
}
@Override
public FlashCard getNextUnseenFlashCard(Collection<Long> seenIds) {
List<FlashCard> unseen;
if (seenIds.size() > 0) {
unseen = flashCardRepository.findByIdNotIn(seenIds);
} else {
unseen = flashCardRepository.findAll();
}
FlashCard card = null;
if (unseen.size() > 0) {
card = unseen.get(new Random().nextInt(unseen.size()));
}
return card;
}
@Override
public FlashCard getNextFlashCardBasedOnViews(Map<Long, Long> idToViewCounts) {
FlashCard card = getNextUnseenFlashCard(idToViewCounts.keySet());
if (card != null) {
return card;
}
Long leastViewedId = null;
for (Map.Entry<Long, Long> entry : idToViewCounts.entrySet()) {
if (leastViewedId == null) {
leastViewedId = entry.getKey();
continue;
}
Long lowestScore = idToViewCounts.get(leastViewedId);
if (entry.getValue() < lowestScore) {
leastViewedId = entry.getKey();
}
}
return flashCardRepository.findOne(leastViewedId);
}
@Override
public List<FlashCard> getRandomFlashCards(int amount) {
List<FlashCard> cards = flashCardRepository.findAll();
Collections.shuffle(cards);
return cards.stream()
.limit(amount)
.collect(toList());
}
}