using UnityEngine;
using System;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class ChaseHeroBehaviour : MonoBehaviour 
{
    private float speed = 3.0f;
	
    private float acceleration = 6.0f;
	
    private float startDistance = 15.0f;
	
    private float stopDistance = 3.0f;


    private Rigidbody myRigidbody { get; set; }

    private Robot myRobot { get; set; }

    private RangedAttackBehaviour myRangedAttackBehaviour { get; set; }

	[SerializeField]
	private GameObject hero;

    private bool isMoving { get; set; }

	private bool isActiveCheck { get; set; }

    void Start()
    {
        myRobot = GetComponent<Robot>();
        myRangedAttackBehaviour = GetComponent<RangedAttackBehaviour>();
        myRigidbody = rigidbody;

        if (hero == null)
        {
            hero = FindObjectOfType<Hero>() ? FindObjectOfType<Hero>().gameObject : null;
        }

        isMoving = false;
    }

    void Update()
    {
		if (!isActiveCheck)
		{
			return;
		}

        if (myRobot == null || hero == null)
        {
            return;
        }

        if (!myRobot.isAlive())
        {
            return;
        }

        if (myRangedAttackBehaviour != null && myRangedAttackBehaviour.isAttacking)
        {
            isMoving = false;
            return;
        }

        Quaternion lookAt = Quaternion.LookRotation(hero.transform.position - transform.position, new Vector3(0.0f, 0.0f, -1.0f));
        transform.rotation = Quaternion.RotateTowards(transform.rotation, lookAt, Time.deltaTime * 200.0f);

        Vector3 toHero = hero.transform.position - myRobot.transform.position;
        float distanceToHero = toHero.magnitude;
            if (myRigidbody != null && distanceToHero > 0.5f)
            {
                Vector3 desiredVelocity = speed * toHero / distanceToHero;
                Vector3 desiredImpulse = desiredVelocity - myRigidbody.velocity;
                Vector3 realImpulse = Vector3.ClampMagnitude(desiredImpulse, acceleration * Time.deltaTime);
                myRigidbody.AddForce(realImpulse, ForceMode.VelocityChange);
            }
            else
            {
                transform.position = Vector3.MoveTowards(transform.position, hero.transform.position, speed * Time.deltaTime);
            }
        
        if (isMoving && (distanceToHero <= stopDistance))
        {
            isMoving = false;
        }
    }

	public bool withinDistance()
	{
		if (hero == null || myRobot == null) 
			return false;
	
		Vector3 toHero = hero.transform.position - myRobot.transform.position;
		if (toHero.magnitude < startDistance)
			return true;
		return false;

	}

	public bool isActive()
	{
		return isActiveCheck;
	}

	public void activate()
	{
		isActiveCheck = true;
        if (audio != null)
        {
            audio.Play();
        }
	}
	public void deactivate()
	{
		isActiveCheck = false;
	}
}
