// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.command;

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

import java.util.Collection;

import javax.swing.JLabel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.visitor.NameVisitor;

/**
 * Command that basically replaces one OSM primitive by another of the 
 * same type.
 *  
 * @author Imi
 */
public class ReplaceSubObjectCommand extends Command {

	// container object in which to replace a sub object
	private final OsmPrimitive parent;

	// the sub-object to be replaced
	private final OsmPrimitive osm;
	// its replacement
	private final OsmPrimitive newOsm;
	private Object cookie;

	public ReplaceSubObjectCommand(OsmPrimitive _parent, OsmPrimitive _osm, OsmPrimitive _newOsm) {
		this.parent = _parent;
		this.osm = _osm;
		this.newOsm = _newOsm;
    }

	@Override public boolean executeCommand() {
	    super.executeCommand();
		cookie = parent.replace(osm, newOsm);
	    parent.modified = true;
		if (cookie == null)
			return false;
		return true;
    }

	@Override public void undoCommand() {
	    super.executeCommand();
		parent.replace(newOsm, osm, cookie);
	    parent.modified = false;
    }

	@Override public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) {
		modified.add(osm);
    }

	@Override public MutableTreeNode description() {
		NameVisitor v = new NameVisitor();
		parent.visit(v);
		return new DefaultMutableTreeNode(new JLabel(tr("ReplaceSubObject")+" "+tr(v.className)+" "+v.name, v.icon, JLabel.HORIZONTAL));
    }
}
