package at.oefai.aaa.animation;

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

/**
 * SVG anim for picking up an object.
 * @author Stefan Rank
 */
public class TakeObjectAtPosition extends BaseSVGAnim {
    private volatile boolean done = false;
    private SVGPoint dest = null;
    private SVGPoint coords = null;
    private String theObject = null;

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

    protected void doFirstTime() {
        assert (this.args.size() == 2) : "wrong arguments for TakeObjectAtPosition";
        this.theObject = this.args.get(0).getString();
        SVGSVGElement eleActor = getNamedElement(this.actor);
        this.dest = getElementsPos(eleActor);
        if (this.dest == null) {
            assert false : "could not get agents (" + this.actor + ") position";
            this.done = true;
        } else {
            // displace the dest for agents carrying stuff
            SVGSVGElement eleObject = getNamedElement(this.theObject);
            if (eleObject == null) {
                assert false : "could not get object (" + this.theObject + ")";
                this.done = true;
            } else {
                this.coords = getCoordsOfAgentsObject(eleObject, eleActor);
                addToSVGPoint(this.dest, this.coords);
                hideElement(this.theObject + SHADOW_POSTFIX);
            }
        }
    }


    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) {
            assert false : "could not get objects (" + this.theObject + ") position";
            this.done = true;
        } else {
            SVGPoint nextPos = getNextObjectPos(curr, this.dest);
            if (nextPos == this.dest) {
                SVGSVGElement eleAgent = getNamedElement(this.actor);
                // take out above element from where it is now:
                eleObject.getParentNode().removeChild(eleObject);
                setElementsPos(eleObject, this.coords);
                // put it under Agent in the tree (which puts it above on screen;-)
                eleAgent.appendChild(eleObject);
                adjustHolding(eleAgent);
                this.done = true;
            } else {
                setElementsPos(eleObject, nextPos);
            }
        }
    }

}
