using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class DragAndDropPart : MonoBehaviour
{
	// The plane the object is currently being dragged on
	private Plane dragPlane;

	// The difference between where the mouse is on the drag plane and 
	// where the origin of the object is on the drag plane
	private Vector3 offset;

	private Camera myMainCamera;

	public HingeJoint2D Joint;
	public AttachmentPoint attachmentPoint;

	public bool Attached;
	bool MotorActive = false;
	public float MotorStrength = 200;
	void Start()
	{
		myMainCamera = Camera.main; // Camera.main is expensive ; cache it here
	}

	private void Update()
	{
		
		if (MotorActive)
		{
			GetComponent<Rigidbody2D>().AddTorque(-MotorStrength*Time.deltaTime);
		}
	}

	public void Detach()
	{
		if (Joint.enabled)
		{
			Joint.enabled = false;
			Joint.connectedBody = null;
			attachmentPoint = null;
			Attached = false;
			Joint.useMotor = false;
			Joint.motor = new JointMotor2D();
		}
	}
	void OnMouseDown()
	{
		if (!MotorActive)
		{
			dragPlane = new Plane(myMainCamera.transform.forward, transform.position);
			Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);

			float planeDist;
			dragPlane.Raycast(camRay, out planeDist);
			offset = transform.position - camRay.GetPoint(planeDist);
		}
	}

	void OnMouseDrag()
	{
		if (!MotorActive)
		{
			Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);

			float planeDist;
			dragPlane.Raycast(camRay, out planeDist);
			transform.position = camRay.GetPoint(planeDist) + offset;
		}
	}
	private void OnMouseUp()
	{
		if (MotorActive)
			return;
		var targets = Physics2D.OverlapCircleAll(transform.position, .25f);
		attachmentPoint = null;
		for (int i = 0; i < targets.Length; ++i)
		{
			if (targets[i].GetComponent<AttachmentPoint>())
			{
				attachmentPoint = targets[i].GetComponent<AttachmentPoint>();
			}
		}
		

		if (attachmentPoint)
		{
			Attach();
		}
		else
			Detach();
	}

	void Attach()
	{
		JointMotor2D motor = new JointMotor2D();
		motor.motorSpeed = 100;
		Joint.useMotor = true;
		Joint.motor = motor;
		Joint.connectedBody = attachmentPoint.GetComponent<Rigidbody2D>();
		Joint.enabled = true;
		Attached = true;
	}

	public void StartMotor()
	{
		MotorActive = true;
	}
}