// (c) MIT 2003.  All rights reserved.

package rec.simulate.widgets.wm;

import rec.util.*;
import java.io.*;
import rec.geo.*;
import rec.core.widgets.*;
import java.math.*;
import rec.simulate.*;
import rec.simulate.widgets.*;

public class WMSimRope extends WSimRope
{

    public WMSimRope( WComplex complex )
    {
	super( complex );
    }

    public WMSimRope( WLine line )
    {
	super( line );
    }

    public String load( WMSimulatorRegistryBase reg ) 
    {
	double length;
	GPoint newEnd1;
	GPoint newEnd2;

	if(m_Components[0] instanceof  GComplex){
	    
	    newEnd1 = reg.convert( ((GComplex)m_Components[0]).getStartPoint() );
	    newEnd2 = reg.convert( ((GComplex)m_Components[0]).getEndPoint() );

	    length = reg.convert(((GComplex) m_Components[0]).getLength());
	}

	else{
	    newEnd1 = reg.convert( ((GSegment)m_Components[0]).getHeadPoint() );
	    newEnd2 = reg.convert( ((GSegment)m_Components[0]).getTailPoint() );

	    length = reg.convert(((GSegment) m_Components[0]).getLength());
	}
	
	String output;

	Console.writeln( "loading rope" );
    
	output = "Dim " + m_Name + " as WMConstraint\n";
      
	// attach the endpoints to bodies, if they are attached to bodies
	// we assume at this point that the bodies have already been loaded
	// otherwise this does not work.
      
	if ( m_headBody != null ) {
	    GPoint newBody1 = reg.convert( m_headBody.getLocation().getCenter() );
	    Console.writeln( "Body1 is at " + newBody1 );
	    newEnd1.x -= newBody1.x;
	    newEnd1.y -= newBody1.y;
	}
	if ( m_tailBody != null ) {
	    GPoint newBody2 = reg.convert( m_tailBody.getLocation().getCenter() );
	    newEnd2.x -= newBody2.x;
	    newEnd2.y -= newBody2.y;
	}

	output +=  "t1.X = " + newEnd1.x + " : t1.Y = " + newEnd1.y + "\n";
	output +=  "t2.X = " + newEnd2.x + " : t2.Y = " + newEnd2.y + "\n";
	output +=  "Set " + m_Name + " = doc.NewConstraint(\"Rope\")\n";

	output += "Set " + m_Name + ".Point(1).PX.Value = " + newEnd1.x + "\n";
	output += "Set " + m_Name + ".Point(1).PY.Value = " + newEnd1.y + "\n";
	output += "Set " + m_Name + ".Point(2).PX.Value = " + newEnd2.x + "\n";
	output += "Set " + m_Name + ".Point(2).PY.Value = " + newEnd2.y + "\n";

	if ( m_headBody != null ) {
	    output +=  "Set " + m_Name + ".Point(1).Body = " + 
		m_headBody.getName() + "\n";
	    Console.writeln( "attatching " + m_Name + " to " + m_headBody.getName() );
	}
	if ( m_tailBody != null ) {
	    output += "Set " + m_Name + ".Point(2).Body = " + m_tailBody.getName() + 
		"\n";
	    Console.writeln( "attatching " + m_Name + " to " + m_tailBody.getName() );
	}



	// set the length
	output += m_Name + ".length.value = " + length + "\n";

	System.out.println(output);

	//	String output = "";
      
	return output;

    }
}
