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

public class Bat : MonoBehaviour
{
    public float speed = 5;
    public float radius = 5;

    private Vector3 initPos;
    private Animator anim;

    private void Awake()
    {
        initPos = transform.position;
        anim = GetComponent<Animator>();
    }

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update ()
    {
        GameObject target = CheckPlayer();
        if (target != null)
        {
            anim.SetInteger("State", 1);
            Vector3 pos = target.transform.position - transform.position;
            transform.Translate(pos.normalized * speed * Time.deltaTime);
        }
        else
        {
            if ((transform.position - initPos).magnitude < 0.1f)
            {
                anim.SetInteger("State", 0);
            }
            else
            {
                anim.SetInteger("State", 1);
                Vector3 pos = initPos - transform.position;
                transform.Translate(pos.normalized * speed * Time.deltaTime);
            }           
        }	
	}

    private GameObject CheckPlayer()
    {
        Collider2D[] colls = Physics2D.OverlapCircleAll(transform.position, radius);

        for (int i = 0; i < colls.Length; i++)
        {
            if(colls[i].gameObject.tag == "Player")
            {
                return colls[i].gameObject;
            }
        }
        return null;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Player player = collision.gameObject.GetComponent<Player>();
        if (player != null)
        {
            player.Die(1);
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.cyan;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}
