using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class VulnerableScript : MonoBehaviour {

	public Vector3 startSpeed;
	public float brakeFactor;
	public Vector3 currentSpeed;
	public List<WaveEmitterScript> waveEmitters;

	// Use this for initialization
	void Start () {
		waveEmitters = new List<WaveEmitterScript> ();
	}

	public void GravityUpdate()
	{
		Vector3 speed = Vector3.zero;
		foreach (WaveEmitterScript waveEmitter in waveEmitters) {
			Vector3 diff = (this.transform.position-waveEmitter.transform.position).normalized;
			float radiusPercentDistance = Vector3.Distance (this.transform.position, waveEmitter.transform.position)/waveEmitter.waveEmissionArea.GetComponent<CircleCollider2D> ().radius;
			speed += (waveEmitter.waveForce * Mathf.Pow(radiusPercentDistance,2) * new Vector3(diff.x, diff.y, 0));
		}
//		Debug.Log (speed);
		currentSpeed += speed;

		if (waveEmitters.Count == 0) {
			Vector3 breakSpeed = -brakeFactor * currentSpeed.normalized;
			currentSpeed += brakeFactor * breakSpeed;
		}

		this.transform.position += new Vector3 (currentSpeed.x, currentSpeed.y, 0)*Time.fixedDeltaTime;
	}

	public void SetFirstImpulse(Vector3 firstImpulseDirection)
	{
		Vector3 speed = Vector3.zero;
		foreach (WaveEmitterScript waveEmitter in waveEmitters) {
			Vector3 diff = (this.transform.position-waveEmitter.transform.position).normalized;
			float radiusPercentDistance = Vector3.Distance (this.transform.position, waveEmitter.transform.position) / waveEmitter.waveEmissionArea.GetComponent<CircleCollider2D> ().radius;
			speed += (waveEmitter.waveForce * Mathf.Pow(radiusPercentDistance,2) * new Vector3(diff.x, diff.y, 0));
		}
		currentSpeed = firstImpulseDirection+speed;
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if (other.transform.parent != null) {
			if (other.transform.parent.GetComponent<WaveEmitterScript>())
			{
				if (other.name.Equals ("WaveEmissionArea")) {
					waveEmitters.Add (other.transform.parent.GetComponent < WaveEmitterScript> ());
				}
			}
		}
	}

	void OnTriggerExit2D(Collider2D other)
	{
		if (other.transform.parent != null) {
			if (other.transform.parent.GetComponent<WaveEmitterScript>())
			{
				if (other.name.Equals ("WaveEmissionArea")) {
					waveEmitters.Remove (other.transform.parent.GetComponent < WaveEmitterScript> ());
				}
			}
		}
	}
}
