package at.oefai.aaa.animation;

import org.w3c.dom.svg.SVGPoint;
import org.w3c.dom.svg.SVGSVGElement;

/**
 * SVG anim for moving an object from somewhere (an agents hand) to a named position.
 * @author Stefan Rank
 */
public class PutDownObjectAtPosition extends BaseSVGAnim {
    private volatile boolean done = false;
    private SVGPoint dest = null;
    private String theObject = null;

    public BaseAnim newInstance() { return new PutDownObjectAtPosition(); }

    protected void doFirstTime() {
        assert (this.args.size() == 2) : "wrong arguments for PutDownObject";
        this.theObject = this.args.get(0).getString();
        this.dest = getNamedPointRandDisplace(this.args.get(1).getString());

        // get the object out of the agent svg and set it to the same pos:
        SVGSVGElement eleActor = getNamedElement(this.actor);
        SVGPoint curr = getElementsPos(eleActor);
        if (curr == null) {
            assert false : "could not get actors (" + this.actor + ") position";
            this.done = true;
        } else {
            SVGSVGElement eleObject = getNamedElement(this.theObject);
            if (eleObject == null) {
                assert false : "could not get object (" + this.theObject + ")";
                this.done = true;
            } else {
                eleObject.getParentNode().removeChild(eleObject);
                adjustHolding(eleActor);
                setElementsPos(eleObject, curr);
                // add the object to the svg doc
                appendObjectToSVGDoc(eleObject);
            }
        }
    }


    public boolean isFinished() {
        return this.done;
    }

    protected void doIt() {
        // move the object if it is still away from the destination
        SVGSVGElement eleObject = getNamedElement(this.theObject);
        SVGPoint curr = getElementsPos(eleObject);
        if (curr == null) {
            this.done = true;
        } else {
            SVGPoint nextPos = getNextObjectPos(curr, this.dest);
            if (nextPos == this.dest) {
                this.done = true;
                showElement(this.theObject + SHADOW_POSTFIX);
            }
            setElementsPos(eleObject, nextPos);
        }
    }

}
