package
{
    import away3d.core.mesh.Vertex;
    import away3d.core.math.Number3D;
    import away3d.core.scene.Object3D;
    import away3dPlus.objects.WireCurve;

    public class RopeEnd 
    {
        public var rope:Rope;
        private var _index:int;
        public var icon:Object3D;
        private var iconHeight:int;
        
        function RopeEnd(rope:Rope, index:int, icon:Object3D=null) {
            this.rope = rope;
            _index = index;
            this.icon = icon;
            if(icon != null) {
                icon.x = position.x;
                icon.y = position.y;
                icon.z = position.z;
                iconHeight = rope.thickness;
                icon.y += iconHeight;
            }
        }
        
        public function get index():int {
            return _index;
        }
        
        public function set index(n:int):void {
            _index = n;
            touch();
        }
        
        public function get vertex():Vertex {
            return rope.wire.vertex(index);
        }
        
        public function get position():Number3D {
            return vertex.position;
        }
        
        // Call this if you change the vertex position 
        public function touch():void {
            if(icon==null)
                return;
                icon.x = position.x;
                icon.y = position.y;
                icon.z = position.z;
            icon.y += iconHeight;            
        }
        
        // Extend the rope at this end
        public function extendTo(v:Vertex, segments:uint):RopeEnd {
            if(_index > 0) {
                // we can append existing wire
                rope.wire.addSegmentedLine(vertex, v, segments);
            }
            else {
                // we have to create a new wire
                var oldWire:WireCurve = rope.rewire();
                //rope.removeChild(oldWire);
                 //rope.wire = new WireCurve(new WireframeMaterial(rope.rgb, rope.alpha, rope.thickness));
                 rope.wire.addSegmentedLine(v, oldWire.vertex(0), segments);
                 rope.wire.addWire(oldWire);
                 rope.updateEnd();
            }
            if(_index != 0)
                _index = rope.wire.vertices.length - 1;
            touch();
            return this;
        }
    }
}