78c3aeb870df178ee5eafadfc7415b5295698c6d
[Sone.git] / src / main / java / net / pterodactylus / sone / template / ImageAccessor.java
1 /*
2  * Sone - ImageAccessor.java - Copyright © 2011–2019 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.template;
19
20 import net.pterodactylus.sone.data.Album;
21 import net.pterodactylus.sone.data.Image;
22 import net.pterodactylus.util.template.Accessor;
23 import net.pterodactylus.util.template.ReflectionAccessor;
24 import net.pterodactylus.util.template.TemplateContext;
25
26 /**
27  * {@link Accessor} implementation for {@link Image} objects. It adds the
28  * following properties:
29  * <ul>
30  * <li>{@code previous}: returns the previous image in the image’s album, or
31  * {@code null} if the image is the first image of its album.</li>
32  * <li>{@code next}: returns the next image in the image’s album, or {@code
33  * null} if the image is the last image of its album.</li>
34  * </ul>
35  */
36 public class ImageAccessor extends ReflectionAccessor {
37
38         /**
39          * {@inheritDoc}
40          */
41         @Override
42         public Object get(TemplateContext templateContext, Object object, String member) {
43                 Image image = (Image) object;
44                 if ("next".equals(member)) {
45                         Album album = image.getAlbum();
46                         int imagePosition = album.getImages().indexOf(image);
47                         if (imagePosition < album.getImages().size() - 1) {
48                                 return album.getImages().get(imagePosition + 1);
49                         }
50                         return null;
51                 } else if ("previous".equals(member)) {
52                         Album album = image.getAlbum();
53                         int imagePosition = album.getImages().indexOf(image);
54                         if (imagePosition > 0) {
55                                 return album.getImages().get(imagePosition - 1);
56                         }
57                         return null;
58                 }
59                 return super.get(templateContext, object, member);
60         }
61
62 }