cs151/hw3/src/model/PhotoAlbumModel.java

106 lines
2.6 KiB
Java

package model;
import strategy.SortingStrategy;
import iterator.AlbumIterator;
import iterator.PhotoIterator;
import java.util.*;
public class PhotoAlbumModel {
private List<Photo> photos;
private SortingStrategy<Photo> sortingStrategy;
private final List<ModelChangeListener> listeners;
private AlbumIterator iterator;
public interface ModelChangeListener {
void onModelChanged();
}
public PhotoAlbumModel() {
photos = new ArrayList<>();
listeners = new ArrayList<>();
iterator = new PhotoIterator(photos);
}
public void addPhoto(Photo photo) {
photos.add(photo);
sortPhotos();
iterator = new PhotoIterator(photos);
notifyListeners();
}
public void deletePhoto(String name) {
Photo currentPhoto = iterator.current();
photos.removeIf(photo -> photo.name().equals(name));
if (photos.isEmpty()) {
iterator = new PhotoIterator(photos);
} else if (currentPhoto != null && currentPhoto.name().equals(name)) {
iterator = new PhotoIterator(photos);
}
notifyListeners();
}
public void setSortingStrategy(SortingStrategy<Photo> strategy) {
this.sortingStrategy = strategy;
sortPhotos();
iterator = new PhotoIterator(photos);
notifyListeners();
}
private void sortPhotos() {
if (sortingStrategy != null) {
photos = sortingStrategy.sort(photos);
iterator = new PhotoIterator(photos);
}
}
public void addListener(ModelChangeListener listener) {
listeners.add(listener);
}
private void notifyListeners() {
for (ModelChangeListener listener : listeners) {
listener.onModelChanged();
}
}
public List<Photo> getPhotos() {
return Collections.unmodifiableList(photos);
}
public Photo getCurrentPhoto() {
try {
return iterator.current();
} catch (NoSuchElementException e) {
return null;
}
}
public boolean hasNext() {
return iterator.hasNext();
}
public boolean hasPrevious() {
return iterator.hasPrevious();
}
public Photo next() {
try {
Photo next = iterator.next();
notifyListeners();
return next;
} catch (NoSuchElementException e) {
return null;
}
}
public Photo previous() {
try {
Photo prev = iterator.previous();
notifyListeners();
return prev;
} catch (NoSuchElementException e) {
return null;
}
}
}