using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class Tank : Ennemie
{
    [SerializeField]
    private float m_thinkingCooldown = 0.5f;
    [SerializeField]
    private Rigidbody2D m_rigidbody;
    [SerializeField]
    private float m_maxSpeed = 5f;

    private float m_currentCooldown;
    private Vector2 m_direction = Vector2.zero;
    private float m_currentAngle;
    private float m_targetAngle;

    #region Unity Callback
    // Update is called once per frame
    protected override void Update()
    {
        base.Update();

        if (IsDead == false)
        {
            m_currentCooldown -= Time.deltaTime;
            if (m_currentCooldown <= 0f)
            {
                Think();

                m_currentCooldown = m_thinkingCooldown;
            }

            // lerp to the direction.
            float angle = Mathf.Atan2(-1f, m_direction.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        }        
    }

    protected void FixedUpdate()
    {
        if (IsDead == false)
        {
            // move the tank.
            Vector2 velocity = Vector2.zero;
            velocity.x = m_direction.x*m_maxSpeed;
            velocity.y = -(m_maxSpeed + (GameManager.ScrollingSpeed));
            m_rigidbody.velocity = velocity;
        }
    }

    private void Think()
    {
        // retarget.
        m_direction = (GameManager.Player.transform.position - transform.position).normalized;
        m_direction.x = Mathf.Clamp(m_direction.x, -0.8f, 0.8f);
    }


    #endregion
}
