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

public class MovIA : MonoBehaviour {

	public int timing = 0;
	public int maxTiming;
	public int phase = 0;

	public float speed = 6f;            // The speed that the player will move at.

	Vector3 movement;                   // The vector to store the direction of the player's movement.
	Rigidbody IARigidbody;          // Reference to the player's rigidbody.
	Animator anim;

	public bool invulnerable = false;
	public int vidas = 3;
	public bool muerto = false;

	void Awake()
	{
		// Set up references.
		IARigidbody = GetComponent<Rigidbody>();
		anim = GetComponent<Animator>();
	}


	void FixedUpdate()
	{
		timing++;
		if (timing == maxTiming) {
			phase++;
			timing = 0;
		}

		if (muerto) {
			movement.Set (0f, 0f, 0f);
		}else if (phase % 4 == 0) {
			movement.Set(1f, 0f, 1f);
		}else if (phase % 4 == 1) {
			movement.Set(1f, 0f, -1f);
		}else if (phase % 4 == 2) {
			movement.Set(-1f, 0f, -1f);
		}else if (phase % 4 == 3) {
			movement.Set(-1f, 0f, 1f);
		}

		// Move the player around the scene.
		Move(movement);

		// Turn the player to face the mouse cursor.
		Turning(movement);

		// Animate the player.
		//  Animating(movement);

	}

	void Move(Vector3 movement)
	{
		// Normalise the movement vector and make it proportional to the speed per second.
		movement = movement.normalized * speed * Time.deltaTime;

		// Move the player to it's current position plus the movement.
		IARigidbody.MovePosition(transform.position + movement);
	}

	void Turning(Vector3 movement)
	{
		// Create a quaternion (rotation) based on looking down the vector from the player to the mouse.
		Quaternion newRotation = Quaternion.LookRotation(movement);

		// Set the player's rotation to this new rotation.
		IARigidbody.MoveRotation(newRotation);

	}
		
	void OnTriggerEnter(Collider col)
	{
		//Si el objeto con el que colisiona es un rayo.
		if(col.gameObject.CompareTag("Rayo")){
			if(GetComponentInChildren<IA>().jumping == false && !invulnerable)
			{
				vidas--;
				if (vidas == 0) {
					//Muere
					print("Muere IA");
                    anim.SetTrigger("Die");
					muerto = true;
				}
				invulnerable = true;
				Invoke ("ResetInvulnerable", 1.5f);
			}
		}
	}

	private void ResetInvulnerable(){
		invulnerable = false;
	} 




	void Animating(Vector3 movement)
	{
		// Create a boolean that is true if either of the input axes is non-zero.
		bool walking = false;

		if(movement.magnitude <= 0.1f)
		{
			walking = true;
		}
		// Tell the animator whether or not the player is walking.
		anim.SetBool("IsWalking", walking);
	}
}
