using UnityEngine;
using System.Collections;

public class IaBot : MonoBehaviour {

    [SerializeField]float m_MovingTurnSpeed = 360;
    [SerializeField]float m_StationaryTurnSpeed = 180;

    public NavMeshAgent agent { get; private set; } // the navmesh agent required for the path finding
    //public ThirdPersonCharacter character { get; private set; } // the character we are controlling
    public Transform target; // target to aim for
    public Transform canon;
    public bool killmode = false;
    public float distanceArret = 10;

    Rigidbody m_Rigidbody;
    bool m_IsGrounded;
    const float k_Half = 0.5f;
    float m_TurnAmount;
    float m_ForwardAmount;

    

    void Start()
    {
        // get the components on the object we need ( should not be null due to require component so no need to check )
        agent = GetComponentInChildren<NavMeshAgent>();
        agent.updateRotation = false;
        agent.updatePosition = true;

        m_Rigidbody = GetComponent<Rigidbody>();
        m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
    }

    private void Update()
    {
        float dist = Vector3.Distance(target.position, transform.position);


        //mode move
        if (target != null && killmode == false)
        {
            agent.SetDestination(target.position);
            Move(agent.desiredVelocity);
        }
       
        //mode kill
        if (dist <= distanceArret)
        {
            
            KillMode();
        }
    }

    public void Move(Vector3 move)
    {
        //orientation
        if (move.magnitude > 1f) move.Normalize();
        move = transform.InverseTransformDirection(move);
        m_TurnAmount = Mathf.Atan2(move.x, move.z);
        m_ForwardAmount = move.z;

        ApplyExtraTurnRotation();
    }


    void ApplyExtraTurnRotation()
    {
        float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
        transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
    }

    void KillMode()
    {
        agent.SetDestination(transform.position);

        //transform.LookAt(target);

        Debug.Log("canon");
        canon.transform.LookAt(target);
        
    }

}

