package eu.dnetlib.ui.gwt.client.util;

import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.SimpleDropController;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * DropController which allows a widget to be dropped on a SimplePanel drop target when the drop
 * target does not yet have a child widget.
 */
public class SetWidgetDropController extends SimpleDropController {

	private final SimplePanel dropTarget;
	private boolean bUpdate;
	private Class<?> clazz;


	public SetWidgetDropController(SimplePanel dropTarget, Class<?> clazz, boolean bUpdate) {
		super(dropTarget);
		this.dropTarget = dropTarget;
		this.bUpdate = bUpdate;
		this.clazz = clazz;
	}

	@Override
	public void onDrop(DragContext context) {
		if (!(context.draggable instanceof DragWidget)) return;

		if (((DragWidget) context.draggable).getClazz() == clazz) {
			dropTarget.setWidget(context.draggable);
			super.onDrop(context);
		}
	}

	@Override
	public void onPreviewDrop(DragContext context) throws VetoDragException {
		if ( !bUpdate && dropTarget.getWidget() != null) {
			throw new VetoDragException();
		}
		super.onPreviewDrop(context);
	}
}
