aboutsummaryrefslogtreecommitdiffstats
path: root/src/eu/equalparts/cardbase/cardstorage/StandaloneCardContainer.java
blob: 52fc89e26d2336be6ee570a9e2c978f7d729c570 (plain)
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
package eu.equalparts.cardbase.cardstorage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;

import eu.equalparts.cardbase.cards.Card;
import eu.equalparts.cardbase.comparator.CardComparator;

public abstract class StandaloneCardContainer extends ReferenceCardContainer {
	
	@JsonProperty private Map<Integer, Card> cardData;
	
	public StandaloneCardContainer() {
		super();
		cardData = new HashMap<>();
	}
	
	@Override
	public void addCard(Card cardToAdd, int count) {
		super.addCard(cardToAdd, count);
		cardData.putIfAbsent(cardToAdd.hashCode(), cardToAdd);
	}

	@Override
	public int removeCard(Card cardToRemove, int count) {
		int removed = super.removeCard(cardToRemove, count);
		if (getCount(cardToRemove) <= 0) {
			cardData.remove(cardToRemove.hashCode());
		}
		return removed;
	}
	
	/**
	 * Returns a card from the cardbase by set code and number.
	 * If no such card is in the cardbase, returns null.
	 * 
	 * @param setCode the set to which the requested card belongs.
	 * @param number the requested card's set number.
	 * @return the requested {@code Card} or null if no card is found.
	 */
	public Card getCard(String setCode, String number) {
		return cardData.get(Card.makeHash(setCode, number));
	}
	
	/**
	 * This method is intended to allow iteration directly on the list of cards,
	 * while at the same time retaining control over the insert and remove procedures.
	 * The returned {@code List} is a read-only; trying to modify its structure will
	 * result in an {@code UnsupportedOperationException}.
	 * 
	 * @return an unmodifiable list of all the cards in the cardbase.
	 */
	public Collection<Card> getCards() {
		return Collections.unmodifiableCollection(cardData.values());
	}
	
	/**
	 * @param fieldName the name of the field by which to sort.
	 * @return an unmodifiable collection representing the cardbase sorted in the required order.
	 * @throws NoSuchFieldException if the field provided is invalid.
	 */
	public Collection<Card> sortByField(String fieldName) throws NoSuchFieldException {
		List<Card> sortedCards = new ArrayList<Card>(getCards());
		sortedCards.sort(new CardComparator(Card.class.getDeclaredField(fieldName)));
		return Collections.unmodifiableCollection(sortedCards);
	}
}