|
| 1 | +package com.woowacourse.ternoko.auth.application; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Random; |
| 7 | +import org.jetbrains.annotations.NotNull; |
| 8 | + |
| 9 | +public class RandomMemberIdGenerator { |
| 10 | + |
| 11 | + final static Random RANDOM = new Random(System.currentTimeMillis()); |
| 12 | + |
| 13 | + final long startCrewId; |
| 14 | + final long endCrewId; |
| 15 | + final long startCoachId; |
| 16 | + final long endCoachId; |
| 17 | + List<Long> crewIds; |
| 18 | + List<Long> coachIds; |
| 19 | + |
| 20 | + public RandomMemberIdGenerator(final long startCrewId, final long endCrewId, final long startCoachId, |
| 21 | + final long endCoachId, |
| 22 | + final List<Long> crewIds, final List<Long> coachIds) { |
| 23 | + this.startCrewId = startCrewId; |
| 24 | + this.endCrewId = endCrewId; |
| 25 | + this.startCoachId = startCoachId; |
| 26 | + this.endCoachId = endCoachId; |
| 27 | + this.crewIds = crewIds; |
| 28 | + this.coachIds = coachIds; |
| 29 | + } |
| 30 | + |
| 31 | + public static RandomMemberIdGenerator of(final long startCrewId, |
| 32 | + final long endCrewId, |
| 33 | + final long startCoachId, |
| 34 | + final long endCoachId) { |
| 35 | + final List<Long> crewIds = getIds(startCrewId, endCrewId); |
| 36 | + |
| 37 | + final List<Long> coachIds = new ArrayList<>(); |
| 38 | + for (long i = startCoachId; i <= endCoachId; i++) { |
| 39 | + coachIds.add(i); |
| 40 | + } |
| 41 | + |
| 42 | + return new RandomMemberIdGenerator(startCrewId, endCrewId, startCoachId, endCoachId, crewIds, coachIds); |
| 43 | + } |
| 44 | + |
| 45 | + @NotNull |
| 46 | + private static List<Long> getIds(final long startId, final long endId) { |
| 47 | + final List<Long> ids = Collections.synchronizedList(new ArrayList<>()); |
| 48 | + for (long i = startId; i <= endId; i++) { |
| 49 | + ids.add(i); |
| 50 | + } |
| 51 | + return ids; |
| 52 | + } |
| 53 | + |
| 54 | + public Long getRandomCrewId() { |
| 55 | + if (crewIds.size() == 0) { |
| 56 | + crewIds = getIds(startCrewId, endCrewId); |
| 57 | + } |
| 58 | + |
| 59 | + final int randomIndex = RANDOM.nextInt(crewIds.size()); |
| 60 | + return crewIds.remove(randomIndex); |
| 61 | + } |
| 62 | + |
| 63 | + public Long getRandomCoachId() { |
| 64 | + if (coachIds.size() == 0) { |
| 65 | + coachIds = getIds(startCoachId, endCoachId); |
| 66 | + } |
| 67 | + |
| 68 | + final int randomIndex = RANDOM.nextInt(coachIds.size()); |
| 69 | + return coachIds.remove(randomIndex); |
| 70 | + } |
| 71 | +} |
0 commit comments