import item.product;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Items {
private static Items instance = null;
private Set<product> products;
private Persisted_Item pItem = Persisted_Item.getInstance();
Items() {
products = Collections.synchronizedSet(new HashSet<product>());
Iterator<Item> iterator = pItem.getAllItems().iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
products.add(new product(item.getId(), item.getPrice(), item
.getDescription(), item.getLocation()));
}
}
public static Items getInstance() {
if (instance == null) {
instance = new Items();
}
return instance;
}
public synchronized product[] getProducts() {
products.clear();
pItem = Persisted_Item.getInstance();
Iterator<Item> iterator = pItem.getAllItems().iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
products.add(new product(item.getId(), item.getPrice(), item
.getDescription(), item.getLocation()));
}
product[] prod = new product[products.size()];
int i = 0;
for (product p : products) {
prod[i] = p;
i++;
}
return prod;
}
public synchronized String addProduct(product product) throws Exception {
if (!products.contains(product)) {
Item it = new Item(product.description, product.location,
product.price);
pItem.insertItem(it);
products.add(product);
return it.getId();
} else {
System.err.println("Item id " + product.id + " exists!");
return null;
}
}
public synchronized void deleteProduct(String id) {
Iterator<product> i = products.iterator();
while (i.hasNext()) {
product p = i.next();
if (p.id.equals(id)) {
// products.remove(p); //throws ConcurrentException
i.remove();
pItem.deleteItem(id);
}
}
}
public synchronized String searchProductByName(String description) {
for (product p : products)
if (p.description.equalsIgnoreCase(description))
return p.id;
else
System.err.println("Item " + description + "not found!");
return null;
}
public synchronized void changeDescription(String id, String description)
throws Exception {
for (product p : products)
if (p.id.equals(id)) {
p.description = description;
pItem.changeDescription(id, description);
}
}
public synchronized void changeLocation(String id, String location)
throws Exception {
for (product p : products)
if (p.id.equals(id)) {
p.location = location;
pItem.changeLocation(id, location);
}
}
public synchronized void changePrice(String id, double price)
throws Exception {
for (product p : products)
if (p.id.equals(id)) {
p.price = price;
pItem.changePrice(id, price);
}
}
public synchronized product getProductWithId(String id) {
for (product p : products)
if (p.id.equals(id))
return p;
return null;
}
}