package at.oefai.aaa.animation;

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

/**
 * SVG anim for binding an agent with the rope.
 * @author Stefan Rank
 */
public class UseRopeOnAgent extends BaseSVGAnim {
    private String theObject = null;
    private volatile boolean done = false;
    private SVGPoint dest = null;

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

    protected void doFirstTime() {
        assert (this.args.size() == 2) : "wrong arguments for UseRopeOnAgent";
        this.theObject = this.args.get(0).getString();
        // get the target agents pos:
        SVGSVGElement eleTarget = getNamedElement(this.args.get(1).getString());
        this.dest = getElementsPos(eleTarget);
        if (this.dest == null) {
            this.done = true;
        } else {
            // 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 the Rope";
                    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) {
                // change the rope to active (bound)
                Element ele = showElement(this.theObject + "Active");
                if (ele == null) {
                    showTextElement(this.theObject, "Active", 0f);
                }
                hideElement(this.theObject + "Inactive");
                this.done = true;
            }
            setElementsPos(eleObject, nextPos);
        }

    }
}
