Handle merging badges when adding to account

This commit is contained in:
Ehren Kret 2021-09-15 17:02:01 -05:00
parent d5ebf2f2ed
commit 16dba09b61
2 changed files with 44 additions and 1 deletions

View File

@ -324,7 +324,24 @@ public class Account {
public void addBadge(AccountBadge badge) {
requireNotStale();
badges.add(badge);
boolean added = false;
for (int i = 0; i < badges.size(); i++) {
AccountBadge badgeInList = badges.get(i);
if (Objects.equals(badgeInList.getId(), badge.getId())) {
if (added) {
badges.remove(i);
i--;
} else {
badges.set(i, badgeInList.mergeWith(badge));
added = true;
}
}
}
if (!added) {
badges.add(badge);
}
purgeStaleBadges();
}

View File

@ -26,6 +26,32 @@ public class AccountBadge {
this.visible = visible;
}
/**
* Returns a new AccountBadge that is a merging of the two originals. IDs must match for this operation to make sense.
* The expiration will be the later of the two.
* Visibility will be set if either of the passed in objects is visible.
*/
public AccountBadge mergeWith(AccountBadge other) {
if (!Objects.equals(other.id, id)) {
throw new IllegalArgumentException("merging badges should only take place for same id");
}
final Instant latestExpiration;
if (expiration == null || other.expiration == null) {
latestExpiration = null;
} else if (expiration.isAfter(other.expiration)) {
latestExpiration = expiration;
} else {
latestExpiration = other.expiration;
}
return new AccountBadge(
id,
latestExpiration,
visible || other.visible
);
}
public String getId() {
return id;
}