using UnityEngine;
using System.Collections;

public class Attachable : MonoBehaviour 
{
	public float AttachRadius = 6.5f;

	public bool CanAttach = false;

	Transform thisTransform;
	Collider2D thisCollider;
	BaseShipComponent baseComponent;

	InputController inputController;

	public System.Action OnAttached; 

	void Awake() 
	{
		thisTransform = transform;
		thisCollider = collider2D;
		baseComponent = GetComponent<BaseShipComponent> ();
		inputController = FindObjectOfType<InputController> ();

		Invoke ("Activate", 0.5f);
	}

	void Activate()
	{
		CanAttach = true;
	}
	
	void Update () 
	{
		if (!CanAttach)
			return;

		Collider2D[] hardpointCheck = Physics2D.OverlapCircleAll(thisTransform.position, AttachRadius);
		Hardpoint closest = null;
		float distance = float.MaxValue;
		foreach (Collider2D collider in hardpointCheck)
		{
			BaseShipComponent b = collider.gameObject.GetComponent<BaseShipComponent>();

			if(b != null && b.Hardpoints != null)
			{
				foreach(Hardpoint h in b.Hardpoints)
				{
					float d = Vector2.Distance(thisTransform.position, h.HardpointTransform.position);
					if(d < distance && collider != thisCollider)
					{
						if(b.HardpointIsValid(h.ID))
						{
							closest = h;
							distance = d;
						}
					}
				}
			}
		}

		if (closest != null) 
		{
			Debug.DrawLine(thisTransform.position, closest.transform.position);

			for(int i = 0 ; i < inputController.playersActiveKey.Length ; i++)
			{
				if(inputController.playersActiveKey[i])
				{
					Attach(closest, (PlayerID) i);
					return;
				}
			}
		}
	}

	void Attach(Hardpoint point, PlayerID player)
	{
		point.Base.AddShipComponent(baseComponent, point.ID, player);
		Destroy(gameObject.GetComponent<RotateAroundShip>());
		if (OnAttached != null) 
		{
			OnAttached();
		}
		Destroy (this);
	}
}
