package model; import strategy.SortingStrategy; import iterator.AlbumIterator; import iterator.PhotoIterator; import java.util.*; public class PhotoAlbumModel { private List photos; private SortingStrategy sortingStrategy; private final List 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 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 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; } } }