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

public class Enemy_controller : MonoBehaviour {

    Animator animator;
    AudioSource audio;

    private bool walk_right;
    private float player_pos; // turn and walk to the player
    private bool player_hidden;
    private bool wait_for_destroy = false;

    // Enemy Setup
    public float speed = 1;

	// Use this for initialization
	void Start ()
    {
        animator = GetComponent<Animator>();
        audio = GetComponent<AudioSource>();
    }
	
	// Update is called once per frame
	void Update ()
    {
        player_pos = GameObject.FindGameObjectWithTag("Player").transform.position.x;
        player_hidden = Player_control.Is_Hidden;

        FindPlayer();
        walk();
        timeup();  // kills the enemy when time is up
	}


    void FindPlayer()
    {
        if (transform.position.x < player_pos & player_hidden == false)
        {
            walk_right = true;
            animator.SetBool("walk_right", true);
        }
        if (transform.position.x > player_pos & player_hidden == false)
        {
            walk_right = false;
            animator.SetBool("walk_right", false);
        }
        if (player_hidden == true)
        {
            animator.SetBool("idle", true);
        }
        else
        {
            animator.SetBool("idle", false);
        }
    }

    void walk()
    {
        if (walk_right == true & player_hidden == false)
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }

        if (walk_right == false & player_hidden == false)
        {
            transform.Translate(Vector3.left * speed * Time.deltaTime);
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            transform.gameObject.tag = "Untagged";
            audio.Play();
            animator.SetBool("dead", true);
            StartCoroutine(Destroy());
            Debug.Log("Hit");
        }
    }

    void timeup()
    {
        if(WaveController.enemy_wave == false & wait_for_destroy == false)
        {
            animator.SetBool("dead", true);
            wait_for_destroy = true;
            StartCoroutine(Destroy_slow());
        }
    }


    IEnumerator Destroy()
    {
        yield return new WaitForSeconds(0.3f);
        Object.Destroy(this.gameObject);
    }

    IEnumerator Destroy_slow()
    {
        yield return new WaitForSeconds(Random.Range(1, 3));
        Object.Destroy(this.gameObject);
    }
}
