Insert a root album into all Sones to get rid of album manipulation in the Sone.
[Sone.git] / src / main / java / net / pterodactylus / sone / data / Album.java
1 /*
2  * Sone - Album.java - Copyright © 2011–2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.data;
19
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Preconditions.checkState;
23 import static java.util.Arrays.asList;
24
25 import java.util.ArrayList;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.UUID;
31
32 import com.google.common.base.Function;
33 import com.google.common.base.Optional;
34 import com.google.common.base.Predicate;
35 import com.google.common.base.Predicates;
36 import com.google.common.collect.Collections2;
37 import com.google.common.collect.FluentIterable;
38 import com.google.common.collect.ImmutableList;
39 import com.google.common.hash.Hasher;
40 import com.google.common.hash.Hashing;
41
42 /**
43  * Container for images that can also contain nested {@link Album}s.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class Album implements Fingerprintable {
48
49         /** Compares two {@link Album}s by {@link #getTitle()}. */
50         public static final Comparator<Album> TITLE_COMPARATOR = new Comparator<Album>() {
51
52                 @Override
53                 public int compare(Album leftAlbum, Album rightAlbum) {
54                         return leftAlbum.getTitle().compareToIgnoreCase(rightAlbum.getTitle());
55                 }
56         };
57
58         /** Function that flattens the given album and all albums beneath it. */
59         public static final Function<Album, List<Album>> FLATTENER = new Function<Album, List<Album>>() {
60
61                 @Override
62                 public List<Album> apply(Album album) {
63                         List<Album> albums = new ArrayList<Album>();
64                         albums.add(album);
65                         for (Album subAlbum : album.getAlbums()) {
66                                 albums.addAll(FluentIterable.from(ImmutableList.of(subAlbum)).transformAndConcat(FLATTENER).toList());
67                         }
68                         return albums;
69                 }
70         };
71
72         /** Function that transforms an album into the images it contains. */
73         public static final Function<Album, List<Image>> IMAGES = new Function<Album, List<Image>>() {
74
75                 @Override
76                 public List<Image> apply(Album album) {
77                         return album.getImages();
78                 }
79         };
80
81         /**
82          * Filter that removes all albums that do not have any images in any album
83          * below it.
84          */
85         public static final Predicate<Album> NOT_EMPTY = new Predicate<Album>() {
86
87                 @Override
88                 public boolean apply(Album album) {
89                         return FluentIterable.from(asList(album)).transformAndConcat(FLATTENER).anyMatch(new Predicate<Album>() {
90
91                                 @Override
92                                 public boolean apply(Album album) {
93                                         return !album.getImages().isEmpty();
94                                 }
95                         });
96                 }
97         };
98
99         /** The ID of this album. */
100         private final String id;
101
102         /** The Sone this album belongs to. */
103         private Sone sone;
104
105         /** Nested albums. */
106         private final List<Album> albums = new ArrayList<Album>();
107
108         /** The image IDs in order. */
109         private final List<String> imageIds = new ArrayList<String>();
110
111         /** The images in this album. */
112         private final Map<String, Image> images = new HashMap<String, Image>();
113
114         /** The parent album. */
115         private Album parent;
116
117         /** The title of this album. */
118         private String title;
119
120         /** The description of this album. */
121         private String description;
122
123         /** The ID of the album picture. */
124         private String albumImage;
125
126         /**
127          * Creates a new album with a random ID.
128          */
129         public Album() {
130                 this(UUID.randomUUID().toString());
131         }
132
133         /**
134          * Creates a new album with the given ID.
135          *
136          * @param id
137          *            The ID of the album
138          */
139         public Album(String id) {
140                 this.id = checkNotNull(id, "id must not be null");
141         }
142
143         //
144         // ACCESSORS
145         //
146
147         /**
148          * Returns the ID of this album.
149          *
150          * @return The ID of this album
151          */
152         public String getId() {
153                 return id;
154         }
155
156         /**
157          * Returns the Sone this album belongs to.
158          *
159          * @return The Sone this album belongs to
160          */
161         public Sone getSone() {
162                 return sone;
163         }
164
165         /**
166          * Sets the owner of the album. The owner can only be set as long as the
167          * current owner is {@code null}.
168          *
169          * @param sone
170          *            The album owner
171          * @return This album
172          */
173         public Album setSone(Sone sone) {
174                 checkNotNull(sone, "sone must not be null");
175                 checkState((this.sone == null) || (this.sone.equals(sone)), "album owner must not already be set to some other Sone");
176                 this.sone = sone;
177                 return this;
178         }
179
180         /**
181          * Returns the nested albums.
182          *
183          * @return The nested albums
184          */
185         public List<Album> getAlbums() {
186                 return new ArrayList<Album>(albums);
187         }
188
189         /**
190          * Adds an album to this album.
191          *
192          * @param album
193          *            The album to add
194          */
195         public void addAlbum(Album album) {
196                 checkNotNull(album, "album must not be null");
197                 checkArgument(album.getSone().equals(sone), "album must belong to the same Sone as this album");
198                 album.setParent(this);
199                 if (!albums.contains(album)) {
200                         albums.add(album);
201                 }
202         }
203
204         /**
205          * Removes an album from this album.
206          *
207          * @param album
208          *            The album to remove
209          */
210         public void removeAlbum(Album album) {
211                 checkNotNull(album, "album must not be null");
212                 checkArgument(album.sone.equals(sone), "album must belong this album’s Sone");
213                 checkArgument(equals(album.parent), "album must belong to this album");
214                 albums.remove(album);
215                 album.removeParent();
216         }
217
218         /**
219          * Moves the given album up in this album’s albums. If the album is already
220          * the first album, nothing happens.
221          *
222          * @param album
223          *            The album to move up
224          * @return The album that the given album swapped the place with, or
225          *         <code>null</code> if the album did not change its place
226          */
227         public Album moveAlbumUp(Album album) {
228                 checkNotNull(album, "album must not be null");
229                 checkArgument(album.sone.equals(sone), "album must belong to the same Sone as this album");
230                 checkArgument(equals(album.parent), "album must belong to this album");
231                 int oldIndex = albums.indexOf(album);
232                 if (oldIndex <= 0) {
233                         return null;
234                 }
235                 albums.remove(oldIndex);
236                 albums.add(oldIndex - 1, album);
237                 return albums.get(oldIndex);
238         }
239
240         /**
241          * Moves the given album down in this album’s albums. If the album is
242          * already the last album, nothing happens.
243          *
244          * @param album
245          *            The album to move down
246          * @return The album that the given album swapped the place with, or
247          *         <code>null</code> if the album did not change its place
248          */
249         public Album moveAlbumDown(Album album) {
250                 checkNotNull(album, "album must not be null");
251                 checkArgument(album.sone.equals(sone), "album must belong to the same Sone as this album");
252                 checkArgument(equals(album.parent), "album must belong to this album");
253                 int oldIndex = albums.indexOf(album);
254                 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
255                         return null;
256                 }
257                 albums.remove(oldIndex);
258                 albums.add(oldIndex + 1, album);
259                 return albums.get(oldIndex);
260         }
261
262         /**
263          * Returns the images in this album.
264          *
265          * @return The images in this album
266          */
267         public List<Image> getImages() {
268                 return new ArrayList<Image>(Collections2.filter(Collections2.transform(imageIds, new Function<String, Image>() {
269
270                         @Override
271                         @SuppressWarnings("synthetic-access")
272                         public Image apply(String imageId) {
273                                 return images.get(imageId);
274                         }
275                 }), Predicates.notNull()));
276         }
277
278         /**
279          * Adds the given image to this album.
280          *
281          * @param image
282          *            The image to add
283          */
284         public void addImage(Image image) {
285                 checkNotNull(image, "image must not be null");
286                 checkNotNull(image.getSone(), "image must have an owner");
287                 checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
288                 if (image.getAlbum() != null) {
289                         image.getAlbum().removeImage(image);
290                 }
291                 image.setAlbum(this);
292                 if (imageIds.isEmpty() && (albumImage == null)) {
293                         albumImage = image.getId();
294                 }
295                 if (!imageIds.contains(image.getId())) {
296                         imageIds.add(image.getId());
297                         images.put(image.getId(), image);
298                 }
299         }
300
301         /**
302          * Removes the given image from this album.
303          *
304          * @param image
305          *            The image to remove
306          */
307         public void removeImage(Image image) {
308                 checkNotNull(image, "image must not be null");
309                 checkNotNull(image.getSone(), "image must have an owner");
310                 checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
311                 imageIds.remove(image.getId());
312                 images.remove(image.getId());
313                 if (image.getId().equals(albumImage)) {
314                         if (images.isEmpty()) {
315                                 albumImage = null;
316                         } else {
317                                 albumImage = images.values().iterator().next().getId();
318                         }
319                 }
320         }
321
322         /**
323          * Moves the given image up in this album’s images. If the image is already
324          * the first image, nothing happens.
325          *
326          * @param image
327          *            The image to move up
328          * @return The image that the given image swapped the place with, or
329          *         <code>null</code> if the image did not change its place
330          */
331         public Image moveImageUp(Image image) {
332                 checkNotNull(image, "image must not be null");
333                 checkNotNull(image.getSone(), "image must have an owner");
334                 checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
335                 checkArgument(image.getAlbum().equals(this), "image must belong to this album");
336                 int oldIndex = imageIds.indexOf(image.getId());
337                 if (oldIndex <= 0) {
338                         return null;
339                 }
340                 imageIds.remove(image.getId());
341                 imageIds.add(oldIndex - 1, image.getId());
342                 return images.get(imageIds.get(oldIndex));
343         }
344
345         /**
346          * Moves the given image down in this album’s images. If the image is
347          * already the last image, nothing happens.
348          *
349          * @param image
350          *            The image to move down
351          * @return The image that the given image swapped the place with, or
352          *         <code>null</code> if the image did not change its place
353          */
354         public Image moveImageDown(Image image) {
355                 checkNotNull(image, "image must not be null");
356                 checkNotNull(image.getSone(), "image must have an owner");
357                 checkArgument(image.getSone().equals(sone), "image must belong to the same Sone as this album");
358                 checkArgument(image.getAlbum().equals(this), "image must belong to this album");
359                 int oldIndex = imageIds.indexOf(image.getId());
360                 if ((oldIndex == -1) || (oldIndex >= (imageIds.size() - 1))) {
361                         return null;
362                 }
363                 imageIds.remove(image.getId());
364                 imageIds.add(oldIndex + 1, image.getId());
365                 return images.get(imageIds.get(oldIndex));
366         }
367
368         /**
369          * Returns the album image of this album, or {@code null} if no album image
370          * has been set.
371          *
372          * @return The image to show when this album is listed
373          */
374         public Image getAlbumImage() {
375                 if (albumImage == null) {
376                         return null;
377                 }
378                 return Optional.fromNullable(images.get(albumImage)).or(images.values().iterator().next());
379         }
380
381         /**
382          * Sets the ID of the album image.
383          *
384          * @param id
385          *            The ID of the album image
386          * @return This album
387          */
388         public Album setAlbumImage(String id) {
389                 this.albumImage = id;
390                 return this;
391         }
392
393         /**
394          * Returns whether this album contains any other albums or images.
395          *
396          * @return {@code true} if this album is empty, {@code false} otherwise
397          */
398         public boolean isEmpty() {
399                 return albums.isEmpty() && images.isEmpty();
400         }
401
402         /**
403          * Returns the parent album of this album.
404          *
405          * @return The parent album of this album, or {@code null} if this album
406          *         does not have a parent
407          */
408         public Album getParent() {
409                 return parent;
410         }
411
412         /**
413          * Sets the parent album of this album.
414          *
415          * @param parent
416          *            The new parent album of this album
417          * @return This album
418          */
419         protected Album setParent(Album parent) {
420                 this.parent = checkNotNull(parent, "parent must not be null");
421                 return this;
422         }
423
424         /**
425          * Removes the parent album of this album.
426          *
427          * @return This album
428          */
429         protected Album removeParent() {
430                 this.parent = null;
431                 return this;
432         }
433
434         /**
435          * Returns the title of this album.
436          *
437          * @return The title of this album
438          */
439         public String getTitle() {
440                 return title;
441         }
442
443         /**
444          * Sets the title of this album.
445          *
446          * @param title
447          *            The title of this album
448          * @return This album
449          */
450         public Album setTitle(String title) {
451                 this.title = checkNotNull(title, "title must not be null");
452                 return this;
453         }
454
455         /**
456          * Returns the description of this album.
457          *
458          * @return The description of this album
459          */
460         public String getDescription() {
461                 return description;
462         }
463
464         /**
465          * Sets the description of this album.
466          *
467          * @param description
468          *            The description of this album
469          * @return This album
470          */
471         public Album setDescription(String description) {
472                 this.description = checkNotNull(description, "description must not be null");
473                 return this;
474         }
475
476         //
477         // FINGERPRINTABLE METHODS
478         //
479
480         /**
481          * {@inheritDoc}
482          */
483         @Override
484         public String getFingerprint() {
485                 Hasher hash = Hashing.sha256().newHasher();
486                 hash.putString("Album(");
487                 hash.putString("ID(").putString(id).putString(")");
488                 hash.putString("Title(").putString(title).putString(")");
489                 hash.putString("Description(").putString(description).putString(")");
490                 if (albumImage != null) {
491                         hash.putString("AlbumImage(").putString(albumImage).putString(")");
492                 }
493
494                 /* add nested albums. */
495                 hash.putString("Albums(");
496                 for (Album album : albums) {
497                         hash.putString(album.getFingerprint());
498                 }
499                 hash.putString(")");
500
501                 /* add images. */
502                 hash.putString("Images(");
503                 for (Image image : getImages()) {
504                         if (image.isInserted()) {
505                                 hash.putString(image.getFingerprint());
506                         }
507                 }
508                 hash.putString(")");
509
510                 hash.putString(")");
511                 return hash.hash().toString();
512         }
513
514         //
515         // OBJECT METHODS
516         //
517
518         /**
519          * {@inheritDoc}
520          */
521         @Override
522         public int hashCode() {
523                 return id.hashCode();
524         }
525
526         /**
527          * {@inheritDoc}
528          */
529         @Override
530         public boolean equals(Object object) {
531                 if (!(object instanceof Album)) {
532                         return false;
533                 }
534                 Album album = (Album) object;
535                 return id.equals(album.id);
536         }
537
538 }