/*
 * @(#)PasteCommand.java 5.1
 *
 */

package CH.ifa.draw.standard;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.util.Enumeration;
import java.util.Vector;

import CH.ifa.draw.util.Clipboard;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.ui.ontology.DrawingView;
import de.renew.draw.ui.ontology.FigureSelection;

/**
 * Command to insert the clipboard into the drawing.
 * See {@link CH.ifa.draw.util.Clipboard}.
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
@SuppressWarnings("removal")
public class PasteCommand extends FigureTransferCommand {

    /**
     * Constructs a paste command.
     * @param name the command name
     */
    public PasteCommand(String name) {
        super(name);
    }

    @Override
    public boolean executeUndoable() {
        DrawingView view = getEditor().view();
        Point lastClick = view.lastClick();
        Point lastPosition = view.getCurrentMousePosition();
        FigureSelection selection = (FigureSelection) Clipboard.getClipboard().getContents();
        if (selection != null) {
            Vector<Figure> figures = selection.getData();
            if (figures.isEmpty()) {
                return false;
            }

            Rectangle r = bounds(figures.elements());
            view.clearSelection();

            if (lastPosition != null) {
                Point lastPositionTransformed = transformPoint(lastPosition, view);
                insertFigures(
                    figures, lastPositionTransformed.x - r.x, lastPositionTransformed.y - r.y);
            } else {
                Point lastClickTransformed = transformPoint(lastClick, view);
                insertFigures(figures, lastClickTransformed.x - r.x, lastClickTransformed.y - r.y);
            }
            view.checkDamage();
            return true;
        }
        return false;
    }

    Rectangle bounds(Enumeration<Figure> k) {
        Rectangle r = (k.nextElement()).displayBox();
        while (k.hasMoreElements()) {
            r.add((k.nextElement()).displayBox());
        }
        return r;
    }

    private Point transformPoint(Point p, DrawingView view) {
        AffineTransform affineTransform = view.getAffineTransform();
        try {
            affineTransform.inverseTransform(p, p);
        } catch (NoninvertibleTransformException e) {
            throw new RuntimeException(e);
        }
        return p;
    }

}