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

package CH.ifa.draw.standard;

import java.awt.Point;
import java.util.Properties;

import CH.ifa.draw.DrawPlugin;
import CH.ifa.draw.framework.UndoableCommand;
import CH.ifa.draw.util.GUIProperties;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.FigureEnumeration;
import de.renew.draw.ui.ontology.DrawingView;
import de.renew.draw.ui.ontology.PointConstrainer;
import de.renew.plugin.PluginProperties;


/**
 * A command to toggle the snap to grid behavior.
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
public class SnapToGridCommand extends UndoableCommand {
    /**
     * Constructs a snap to grid command.
     * @param name the command name
     */
    public SnapToGridCommand(String name) {
        super(name);
    }

    @Override
    public boolean isExecutable() {
        if (!super.isExecutable()) {
            return false;
        }
        return getEditor().view().selectionCount() > 0;
    }

    @Override
    public boolean executeUndoable() {
        DrawingView view = getEditor().view();
        PointConstrainer grid = view.getConstrainer();
        if (grid == null) {
            int size;
            DrawPlugin current = DrawPlugin.getCurrent();
            if (current == null) {
                Properties properties = GUIProperties.getProperties();
                size = ((PluginProperties) properties)
                    .getIntProperty(DrawPlugin.CH_IFA_DRAW_GRID_SIZE, 5);
            } else {
                current.showStatus("No active grid - using default grid.");
                size = current.getProperties().getIntProperty(DrawPlugin.CH_IFA_DRAW_GRID_SIZE, 5);
            }
            grid = new GridConstrainer(size, size);
        }

        FigureEnumeration selection = view.selectionElements();

        while (selection.hasMoreElements()) {
            Figure f = selection.nextFigure();
            Point c = f.center();
            Point cc = grid.constrainPoint(f.center());
            f.moveBy(cc.x - c.x, cc.y - c.y);
        }
        view.checkDamage();
        return true;
    }
}