001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.command;
003
004import static org.openstreetmap.josm.tools.I18n.trn;
005
006import java.util.Collection;
007import java.util.Collections;
008import java.util.HashSet;
009import java.util.Objects;
010
011import org.openstreetmap.josm.data.osm.DataSet;
012import org.openstreetmap.josm.data.osm.OsmPrimitive;
013
014/**
015 * Command that selects OSM primitives
016 *
017 * @author Landwirt
018 */
019public class SelectCommand extends Command {
020
021    /** the primitives to select when executing the command */
022    private final Collection<OsmPrimitive> newSelection;
023
024    /** the selection before applying the new selection */
025    private Collection<OsmPrimitive> oldSelection;
026
027    /**
028     * Constructs a new select command.
029     * @param dataset The dataset the selection belongs to
030     * @param newSelection the primitives to select when executing the command.
031     * @since 12349
032     */
033    public SelectCommand(DataSet dataset, Collection<OsmPrimitive> newSelection) {
034        super(dataset);
035        if (newSelection == null || newSelection.isEmpty()) {
036            this.newSelection = Collections.emptySet();
037        } else {
038            this.newSelection = new HashSet<>(newSelection);
039        }
040    }
041
042    @Override
043    public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) {
044        // Do nothing
045    }
046
047    @Override
048    public void undoCommand() {
049        ensurePrimitivesAreInDataset();
050
051        getAffectedDataSet().setSelected(oldSelection);
052    }
053
054    @Override
055    public boolean executeCommand() {
056        ensurePrimitivesAreInDataset();
057
058        oldSelection = getAffectedDataSet().getSelected();
059        getAffectedDataSet().setSelected(newSelection);
060        return true;
061    }
062
063    @Override
064    public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
065        return Collections.unmodifiableCollection(newSelection);
066    }
067
068    @Override
069    public String getDescriptionText() {
070        int size = newSelection != null ? newSelection.size() : 0;
071        return trn("Selected {0} object", "Selected {0} objects", size, size);
072    }
073
074    @Override
075    public int hashCode() {
076        return Objects.hash(super.hashCode(), newSelection, oldSelection);
077    }
078
079    @Override
080    public boolean equals(Object obj) {
081        if (this == obj) return true;
082        if (obj == null || getClass() != obj.getClass()) return false;
083        if (!super.equals(obj)) return false;
084        SelectCommand that = (SelectCommand) obj;
085        return Objects.equals(newSelection, that.newSelection) &&
086                Objects.equals(oldSelection, that.oldSelection);
087    }
088}