using UnityEngine;
using System.Collections;

public class Emi : MonoBehaviour {

    private PlayerStats stats;
    private Transform player;
    public Animator anim;

    private bool started = false;

    private CharacterController cc;

    private float movespeed = 5.0f;

    private bool thrown = false;

    public GameObject ball;

    private float ballDelay = 0.0f;

    public GameObject theWall;

	// Use this for initialization
    void Start() {
        stats = FindObjectOfType<PlayerStats>();
        player = stats.transform;
        cc = GetComponent<CharacterController>();
	
	}
	
	// Update is called once per frame
	void Update () {

       


        Vector3 toPlayer = player.position - transform.position;
        Vector3 target = toPlayer;
        target = new Vector3(target.x, 0, target.z);
        float step = 5.0f * Time.deltaTime;
        Vector3 newDir = Vector3.RotateTowards(transform.forward, target, step, 0.0F);
        transform.rotation = Quaternion.LookRotation(newDir);


        if (ballDelay > 0) {
            ballDelay -= Time.deltaTime;

            if (ballDelay <= 0) {
                Rigidbody rb;
                rb = Instantiate(ball, transform.position + transform.forward * 2, transform.rotation) as Rigidbody;
                rb.AddForce((toPlayer.normalized + Vector3.up) * 280);

                CameraFollow cf = FindObjectOfType<CameraFollow>();
                cf.startZoom(rb.transform);
            }
        }


        if (stats.health <= 10) {
            if (!started) {
                CameraFollow cf = FindObjectOfType<CameraFollow>();
                cf.startZoom(this.transform);
                theWall.SetActive(false);
                started = true;
            }

            if (toPlayer.magnitude > 10) { 
                cc.Move((transform.forward + Vector3.up * -8) * Time.deltaTime * movespeed);
            } else {
                if (!thrown) {
                    thrown = true;
                    anim.SetTrigger("capture");
                    ballDelay = 0.5f;
                }
            }
        }

	}
}
