using UnityEngine;
using UnityEngine.Events;


namespace GameEngine
{
	[RequireComponent(typeof (Rigidbody2D))]
	public class Projectile : MonoBehaviour
	{
		[SerializeField] private LayerMask m_GroundLayer = default(LayerMask);
		[SerializeField] private LayerMask m_EntityLayer = default(LayerMask);
		[SerializeField] private LayerMask m_RaycastLayer = default(LayerMask);
		private Vector2 _velocity;




		public event UnityAction<Projectile, RaycastHit2D> OnGroundHit;


		public event UnityAction<Projectile, RaycastHit2D, ProjectileTarget> OnProjectileTargetHit; 




		private void FixedUpdate()
		{
			float angle = Mathf.Atan2(_velocity.y, _velocity.x) * Mathf.Rad2Deg;

			float distance = _velocity.magnitude*Time.fixedDeltaTime;
			RaycastHit2D hit = Physics2D.Raycast(transform.position, _velocity, distance, m_RaycastLayer);

			if (hit.transform == null)
			{
				transform.position += (Vector3)_velocity.normalized*distance;
				transform.rotation = Quaternion.Euler(0f,0f,angle);
			}
			else
			{
				if (OnGroundHit != null)
				{
					int collisionLayer = 1 << hit.collider.gameObject.layer;
					if ((m_GroundLayer.value & collisionLayer) == collisionLayer)
					{
						OnGroundHit(this, hit);
						return;
					}
				}

				ProjectileTarget target = hit.collider.GetComponent<ProjectileTarget>();

				if (target != null &&
					OnProjectileTargetHit != null)
				{
					OnProjectileTargetHit(this, hit, target);
				}
			}

			_velocity += Physics2D.gravity * Time.deltaTime;
		}


		public void Initialize(Vector2 position, Vector2 velocity)
		{
			transform.position = position;
			transform.right = velocity.normalized;
			_velocity = velocity;
		}
	}
}
