001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.event.ActionEvent;
007import java.util.Collections;
008import java.util.HashMap;
009import java.util.Map;
010import java.util.function.IntFunction;
011import java.util.function.Supplier;
012
013import javax.swing.AbstractAction;
014import javax.swing.ListSelectionModel;
015
016import org.openstreetmap.josm.command.ChangePropertyCommand;
017import org.openstreetmap.josm.data.UndoRedoHandler;
018import org.openstreetmap.josm.data.osm.OsmPrimitive;
019import org.openstreetmap.josm.gui.util.TableHelper;
020import org.openstreetmap.josm.tools.ImageProvider;
021
022/**
023 * Obtains the selected key and values from a table and restores those properties on the specified primitive.
024 *
025 * @since 16593
026 */
027public class RestorePropertyAction extends AbstractAction {
028
029    private final IntFunction<String> keyFn;
030    private final IntFunction<String> valueFn;
031    private final Supplier<OsmPrimitive> objectSp;
032    private final ListSelectionModel selectionModel;
033
034    /**
035     * Constructs a new {@code RestorePropertyAction}.
036     *
037     * @param keyFn          a function which returns the selected key for a given row index
038     * @param valueFn        a function which returns the selected value for a given row index
039     * @param objectSp       a supplier which returns the selected tagged object
040     * @param selectionModel selection model
041     */
042    public RestorePropertyAction(IntFunction<String> keyFn, IntFunction<String> valueFn,
043                                 Supplier<OsmPrimitive> objectSp, ListSelectionModel selectionModel) {
044        super(tr("Restore selected tags"));
045        this.keyFn = keyFn;
046        this.valueFn = valueFn;
047        this.objectSp = objectSp;
048        this.selectionModel = selectionModel;
049        new ImageProvider("undo").getResource().attachImageIcon(this, true);
050    }
051
052    @Override
053    public void actionPerformed(ActionEvent e) {
054        OsmPrimitive primitive = objectSp.get();
055        if (primitive == null) return;
056
057        Map<String, String> changes = TableHelper.selectedIndices(selectionModel).boxed()
058                .collect(HashMap::new, (m, i) -> m.put(keyFn.apply(i), valueFn.apply(i)), HashMap::putAll);
059        ChangePropertyCommand command = new ChangePropertyCommand(Collections.singleton(primitive), changes);
060        UndoRedoHandler.getInstance().add(command);
061    }
062}