using UnityEngine;
using System.Collections;

public class Magnetism : MonoBehaviour {

	public GameObject StationRing;
	private ConfigurableJoint joint;
	private GameObject Ship;
	private bool FlapsOpen = false;
	private bool Connected = false;
	private GameObject Text;
	private GameObject Warnings;

	private Vector3 CAnchorStart = new Vector3( 0f, 2.541671f, 0f );

	private float MinDist = 10f;

	// Use this for initialization
	void Start () {
		joint = (ConfigurableJoint)gameObject.GetComponent<ConfigurableJoint>();
		Ship = GameObject.Find("Ship");
		Text = GameObject.Find("Stats");
		Warnings = GameObject.Find("Warnings");
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		//Debug.Log( "Ring pos: " + transform.position + "    Station Ring pos " + StationRing.transform.position );
		float SqrDist = (StationRing.transform.position - transform.position).sqrMagnitude;
		if ( !FlapsOpen && SqrDist < 65f ) {
			GameObject StationFlaps = StationRing.transform.FindChild("Flaps").gameObject;
			StationFlaps.animation.Play("open");

			GameObject ShipFlaps = transform.FindChild("Flaps").gameObject;
			ShipFlaps.animation.Play("open");

			FlapsOpen = true;
		}

		if ( FlapsOpen && SqrDist < 1f ) {
			//Debug.Log( "Distance < 1m" );
		}
		if ( !Connected && SqrDist < 0.001f ) {
			Warnings.guiText.text = "Connected!";
			// TODO NEEDS A DELAY TODO
			// without any delay, you can ram at stupid high speed as long as you are lined up
			Connected = true;

			joint.breakForce = 0.5f; // 100x
			joint.breakTorque = 0.5f; // 100x

			GameObject Station = GameObject.Find("Space Station");
			rigidbody.mass = 100f;
			rigidbody.velocity = Station.rigidbody.velocity;
			Destroy(Station.rigidbody);
			Station.transform.parent = transform;

			GameObject StationFlaps = StationRing.transform.FindChild("Flaps").gameObject;
			StationFlaps.animation.Play("lock");
			
			GameObject ShipFlaps = transform.FindChild("Flaps").gameObject;
			ShipFlaps.animation.Play("lock");

			//joint.breakForce = 0.01f; // 10x
			//joint.breakTorque = 0.05f; // 10x
		} else if ( FlapsOpen && SqrDist < 0.01f ) {
			//Debug.Log( "Distance < 1cm " + (StationRing.transform.position - transform.position)*100F );
			Vector3 Normal = (StationRing.transform.position - transform.position).normalized;
			// perfect seal ( 0.0, 0.0, 0.008 )
			if ( SqrDist < MinDist ) {
				MinDist = SqrDist;
				//Debug.Log ( MinDist );
				Vector3 TargetPos = StationRing.transform.position;
				Vector3 Movement = (StationRing.transform.position - transform.position);
				rigidbody.MovePosition( transform.position + Movement/10f );
			}
		}


		if ( Connected && Ship.transform.InverseTransformPoint(transform.position).y > -1.0f) {
			if ( Input.GetKey("g") ) {
				Rigidbody ShipBody = joint.connectedBody;
				joint.connectedBody = null;
				transform.position -= transform.forward*Time.fixedDeltaTime*0.1f ;
				joint.connectedBody = ShipBody;
			}
		}

	}
}
