// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui.dialogs.relation.actions;

import static org.openstreetmap.josm.tools.I18n.tr;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;

import org.openstreetmap.josm.actions.mapmode.DeleteAction;
import org.openstreetmap.josm.data.osm.Relation;
import org.openstreetmap.josm.gui.MainApplication;
import org.openstreetmap.josm.gui.dialogs.relation.GenericRelationEditor;
import org.openstreetmap.josm.gui.dialogs.relation.RelationDialogManager;
import org.openstreetmap.josm.gui.layer.OsmDataLayer;
import org.openstreetmap.josm.tools.ImageProvider;

/**
 * Delete the currently edited relation.
 * @since 9496
 */
public class DeleteCurrentRelationAction extends AbstractRelationEditorAction {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new {@code DeleteCurrentRelationAction}.
     * @param editorAccess An interface to access the relation editor contents.
     */
    public DeleteCurrentRelationAction(IRelationEditorActionAccess editorAccess) {
        super(editorAccess);
        putValue(SHORT_DESCRIPTION, tr("Delete the currently edited relation"));
        new ImageProvider("dialogs", "delete").getResource().attachImageIcon(this, true);
        putValue(NAME, tr("Delete"));
        updateEnabledState();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Relation toDelete = getEditor().getRelation();
        if (toDelete == null)
            return;
        if (toDelete.isDeleted()) {
            // see #23447
            OsmDataLayer layer = MainApplication.getLayerManager().getEditLayer();
            if (layer != null) {
                RelationDialogManager.getRelationDialogManager().close(layer, toDelete);
            }
            return;
        }
        DeleteAction.deleteRelation(getLayer(), toDelete);
    }

    @Override
    protected void updateEnabledState() {
        setEnabled(getEditor().getRelationSnapshot() != null);
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        // Do not call super.
        if (GenericRelationEditor.RELATION_SNAPSHOT_PROP.equals(evt.getPropertyName())) {
            updateEnabledState();
        }
    }
}
