using UnityEngine;
using System.Collections;

[RequireComponent(typeof(CharacterController))]
public class DarkEye : Enemy {

    public float speed = 1.5f;
    public float chaseDistance = 4f;

    private Vector3 originalPosition;
    private Vector3 originalRotation;
    private CharacterController controller;
    private EyeState state;

    enum EyeState
    {
        Guard = 0,
        ReturnToGuard,
        Follow
    };

	void Start () 
    {
        base.Init();
        controller = gameObject.GetComponent<CharacterController>();
        originalPosition = transform.position;
        originalRotation = transform.forward;
	}
	
	void Update () 
    {
        if (isRealForm)
            return;

        switch (state)
        {
            case EyeState.Guard:
                {
                }
                break;
            case EyeState.Follow:
                {
                    // Stop following the player if he's scared
                    if (playerComponent.IsScared)
                    {
                        state = EyeState.ReturnToGuard;
                        return;
                    }

                    // Follow the player until he runs far enough, or gets scared
                    Vector3 moveDirection = player.position - transform.position;
                    if (moveDirection.magnitude > chaseDistance)
                    {
                        state = EyeState.ReturnToGuard;
                        return;
                    }
                    moveDirection.Normalize();
                    controller.Move(moveDirection * Time.deltaTime * speed);

                    if (moveDirection != Vector3.zero)
                        transform.forward = moveDirection;
                }
                break;
            case EyeState.ReturnToGuard:
                {
                    // Go back to the original position
                    Vector3 moveDirection = originalPosition - transform.position;
                    if (moveDirection.magnitude > 0.1f)
                    {
                        moveDirection.Normalize();
                        controller.Move(moveDirection * Time.deltaTime * speed);
                    }
                    else
                    {
                        transform.position = originalPosition;
                        transform.forward = originalRotation;
                        state = EyeState.Guard;
                        return;
                    }

                    if (moveDirection != Vector3.zero)
                        transform.forward = Vector3.Slerp(transform.forward, moveDirection, Time.time);
                }
                break;
        }

        CheckLightSources();
        CheckPlayerPosition();
	}

    void OnTriggerEnter(Collider other)
    {
        if (state == EyeState.Guard)
            state = EyeState.Follow;
    }
}
