001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm;
003
004import java.time.Instant;
005import java.util.ArrayList;
006import java.util.Collection;
007import java.util.Collections;
008import java.util.Comparator;
009import java.util.HashSet;
010import java.util.List;
011import java.util.Map;
012import java.util.Set;
013
014import org.openstreetmap.josm.data.Data;
015import org.openstreetmap.josm.data.DataSource;
016import org.openstreetmap.josm.data.UserIdentityManager;
017import org.openstreetmap.josm.data.coor.LatLon;
018import org.openstreetmap.josm.data.notes.Note;
019import org.openstreetmap.josm.data.notes.Note.State;
020import org.openstreetmap.josm.data.notes.NoteComment;
021import org.openstreetmap.josm.tools.ListenerList;
022import org.openstreetmap.josm.tools.Logging;
023import org.openstreetmap.josm.tools.Utils;
024
025/**
026 * Class to hold and perform operations on a set of notes
027 */
028public class NoteData implements Data {
029
030    /**
031     * A listener that can be informed on note data changes.
032     * @author Michael Zangl
033     * @since 12343
034     */
035    public interface NoteDataUpdateListener {
036        /**
037         * Called when the note data is updated
038         * @param data The data that was changed
039         */
040        void noteDataUpdated(NoteData data);
041
042        /**
043         * The selected node was changed
044         * @param noteData The data of which the selected node was changed
045         */
046        void selectedNoteChanged(NoteData noteData);
047    }
048
049    private long newNoteId = -1;
050
051    private final Storage<Note> noteList;
052    private Note selectedNote;
053    private Comparator<Note> comparator = Note.DEFAULT_COMPARATOR;
054
055    private final ListenerList<NoteDataUpdateListener> listeners = ListenerList.create();
056
057    private final Set<DataSource> dataSourceSet = new HashSet<>();
058
059    /**
060     * Construct a new note container without notes
061     * @since 14101
062     */
063    public NoteData() {
064        this(null);
065    }
066
067    /**
068     * Construct a new note container with a given list of notes
069     * @param notes The list of notes to populate the container with
070     */
071    public NoteData(Collection<Note> notes) {
072        noteList = new Storage<>();
073        if (notes != null) {
074            for (Note note : notes) {
075                noteList.add(note);
076                if (note.getId() <= newNoteId) {
077                    newNoteId = note.getId() - 1;
078                }
079            }
080        }
081    }
082
083    /**
084     * Returns the notes stored in this layer
085     * @return collection of notes
086     */
087    public Collection<Note> getNotes() {
088        return Collections.unmodifiableCollection(noteList);
089    }
090
091    /**
092     * Returns the notes stored in this layer sorted according to {@link #comparator}
093     * @return sorted collection of notes
094     */
095    public Collection<Note> getSortedNotes() {
096        final List<Note> list = new ArrayList<>(noteList);
097        list.sort(comparator);
098        return list;
099    }
100
101    /**
102     * Returns the currently selected note
103     * @return currently selected note
104     */
105    public Note getSelectedNote() {
106        return selectedNote;
107    }
108
109    /**
110     * Set a selected note. Causes the dialog to select the note and
111     * the note layer to draw the selected note's comments.
112     * @param note Selected note. Null indicates no selection
113     */
114    public void setSelectedNote(Note note) {
115        selectedNote = note;
116        listeners.fireEvent(l -> l.selectedNoteChanged(this));
117    }
118
119    /**
120     * Return whether or not there are any changes in the note data set.
121     * These changes may need to be either uploaded or saved.
122     * @return true if local modifications have been made to the note data set. False otherwise.
123     */
124    public synchronized boolean isModified() {
125        for (Note note : noteList) {
126            if (note.getId() < 0) { //notes with negative IDs are new
127                return true;
128            }
129            for (NoteComment comment : note.getComments()) {
130                if (comment.isNew()) {
131                    return true;
132                }
133            }
134        }
135        return false;
136    }
137
138    /**
139     * Merge notes from an existing note data.
140     * @param from existing note data
141     * @since 13437
142     */
143    public synchronized void mergeFrom(NoteData from) {
144        if (this != from) {
145            addNotes(from.noteList);
146            from.getDataSources().forEach(this::addDataSource);
147        }
148    }
149
150    /**
151     * Add notes to the data set. It only adds a note if the ID is not already present
152     * @param newNotes A list of notes to add
153     */
154    public synchronized void addNotes(Collection<Note> newNotes) {
155        for (Note newNote : newNotes) {
156            if (!noteList.contains(newNote)) {
157                noteList.add(newNote);
158            } else {
159                final Note existingNote = noteList.get(newNote);
160                final boolean isDirty = existingNote.getComments().stream().anyMatch(NoteComment::isNew);
161                if (!isDirty) {
162                    noteList.put(newNote);
163                } else {
164                    // TODO merge comments?
165                    Logging.info("Keeping existing note id={0} with uncommitted changes", String.valueOf(newNote.getId()));
166                }
167            }
168            if (newNote.getId() <= newNoteId) {
169                newNoteId = newNote.getId() - 1;
170            }
171        }
172        dataUpdated();
173    }
174
175    /**
176     * Create a new note
177     * @param location Location of note
178     * @param text Required comment with which to open the note
179     */
180    public synchronized void createNote(LatLon location, String text) {
181        if (Utils.isEmpty(text)) {
182            throw new IllegalArgumentException("Comment can not be blank when creating a note");
183        }
184        Note note = new Note(location);
185        note.setCreatedAt(Instant.now());
186        note.setState(State.OPEN);
187        note.setId(newNoteId--);
188        NoteComment comment = new NoteComment(Instant.now(), getCurrentUser(), text, NoteComment.Action.OPENED, true);
189        note.addComment(comment);
190        if (Logging.isDebugEnabled()) {
191            Logging.debug("Created note {0} with comment: {1}", note.getId(), text);
192        }
193        noteList.add(note);
194        dataUpdated();
195    }
196
197    /**
198     * Add a new comment to an existing note
199     * @param note Note to add comment to. Must already exist in the layer
200     * @param text Comment to add
201     */
202    public synchronized void addCommentToNote(Note note, String text) {
203        if (!noteList.contains(note)) {
204            throw new IllegalArgumentException("Note to modify must be in layer");
205        }
206        if (note.getState() == State.CLOSED) {
207            throw new IllegalStateException("Cannot add a comment to a closed note");
208        }
209        if (Logging.isDebugEnabled()) {
210            Logging.debug("Adding comment to note {0}: {1}", note.getId(), text);
211        }
212        NoteComment comment = new NoteComment(Instant.now(), getCurrentUser(), text, NoteComment.Action.COMMENTED, true);
213        note.addComment(comment);
214        dataUpdated();
215    }
216
217    /**
218     * Close note with comment
219     * @param note Note to close. Must already exist in the layer
220     * @param text Comment to attach to close action, if desired
221     */
222    public synchronized void closeNote(Note note, String text) {
223        if (!noteList.contains(note)) {
224            throw new IllegalArgumentException("Note to close must be in layer");
225        }
226        if (note.getState() != State.OPEN) {
227            throw new IllegalStateException("Cannot close a note that isn't open");
228        }
229        if (Logging.isDebugEnabled()) {
230            Logging.debug("closing note {0} with comment: {1}", note.getId(), text);
231        }
232        Instant now = Instant.now();
233        note.addComment(new NoteComment(now, getCurrentUser(), text, NoteComment.Action.CLOSED, true));
234        note.setState(State.CLOSED);
235        note.setClosedAt(now);
236        dataUpdated();
237    }
238
239    /**
240     * Reopen a closed note.
241     * @param note Note to reopen. Must already exist in the layer
242     * @param text Comment to attach to the reopen action, if desired
243     */
244    public synchronized void reOpenNote(Note note, String text) {
245        if (!noteList.contains(note)) {
246            throw new IllegalArgumentException("Note to reopen must be in layer");
247        }
248        if (note.getState() != State.CLOSED) {
249            throw new IllegalStateException("Cannot reopen a note that isn't closed");
250        }
251        Logging.debug("reopening note {0} with comment: {1}", note.getId(), text);
252        NoteComment comment = new NoteComment(Instant.now(), getCurrentUser(), text, NoteComment.Action.REOPENED, true);
253        note.addComment(comment);
254        note.setState(State.OPEN);
255        dataUpdated();
256    }
257
258    private void dataUpdated() {
259        listeners.fireEvent(l -> l.noteDataUpdated(this));
260    }
261
262    private static User getCurrentUser() {
263        return UserIdentityManager.getInstance().asUser();
264    }
265
266    /**
267     * Updates notes with new state. Primarily to be used when updating the
268     * note layer after uploading note changes to the server.
269     * @param updatedNotes Map containing the original note as the key and the updated note as the value
270     */
271    public synchronized void updateNotes(Map<Note, Note> updatedNotes) {
272        for (Map.Entry<Note, Note> entry : updatedNotes.entrySet()) {
273            Note oldNote = entry.getKey();
274            Note newNote = entry.getValue();
275            boolean reindex = oldNote.hashCode() != newNote.hashCode();
276            if (reindex) {
277                noteList.removeElem(oldNote);
278            }
279            oldNote.updateWith(newNote);
280            if (reindex) {
281                noteList.add(oldNote);
282            }
283        }
284        dataUpdated();
285    }
286
287    /**
288     * Returns the current comparator being used to sort the note list.
289     * @return The current comparator being used to sort the note list
290     */
291    public Comparator<Note> getCurrentSortMethod() {
292        return comparator;
293    }
294
295    /** Set the comparator to be used to sort the note list. Several are available
296     * as public static members of this class.
297     * @param comparator - The Note comparator to sort by
298     */
299    public void setSortMethod(Comparator<Note> comparator) {
300        this.comparator = comparator;
301        dataUpdated();
302    }
303
304    /**
305     * Adds a listener that listens to node data changes
306     * @param listener The listener
307     */
308    public void addNoteDataUpdateListener(NoteDataUpdateListener listener) {
309        listeners.addListener(listener);
310    }
311
312    /**
313     * Removes a listener that listens to node data changes
314     * @param listener The listener
315     */
316    public void removeNoteDataUpdateListener(NoteDataUpdateListener listener) {
317        listeners.removeListener(listener);
318    }
319
320    @Override
321    public Collection<DataSource> getDataSources() {
322        return Collections.unmodifiableSet(this.dataSourceSet);
323    }
324
325    /**
326     * Adds a new data source.
327     * @param source data source to add
328     * @return {@code true} if the collection changed as a result of the call
329     * @since 18868
330     */
331    public synchronized boolean addDataSource(DataSource source) {
332        return this.dataSourceSet.add(source);
333    }
334}