using UnityEngine;
using System.Collections;

public class DudeScript : MonoBehaviour {

    public enum DudeState {
        Init,
        Idle,
        Move
    }

    public DudeState State { get; private set; }
    float moveSpeed;
    bool moving;

    public void ChangeMoving() {
        this.moving = !this.moving;
    }

    void Awake() {
        this.State = DudeState.Init;
    }

	// Use this for initialization
    void Start() {
        this.StartCoroutine(InitState());
	}
	
	// Update is called once per frame
	void Update () {
    }

    #region State Routine

    IEnumerator InitState() {
        // Enter
        this.moveSpeed = 30;
        this.moving = false;
        yield return null;

        // Excute
        this.State = DudeState.Idle;
        yield return null;

        // Exit
        NextState();
    }

    IEnumerator IdleState() {
        // Enter
        this.gameObject.animation.Stop();
        yield return null;

        while (this.State == DudeState.Idle) {
            // Excute
            if (moving) {
                this.State = DudeState.Move;
            }

            yield return null;
        }

        // Exit
        NextState();
    }

    IEnumerator MoveState() {
        // Enter
        this.gameObject.animation.Play("Take 001");
        yield return null;

        while (this.State == DudeState.Move) {
            // Excute
            this.gameObject.transform.position +=
                new Vector3(0, 0, Time.deltaTime * moveSpeed);

            if (!moving) {
                this.State = DudeState.Idle;
            }

            yield return null;
        }

        // Exit
        NextState();
    }

    #endregion

    protected void NextState() {
        string methodName = State.ToString() + "State";
        System.Reflection.MethodInfo info = GetType().GetMethod(methodName,
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        StartCoroutine((IEnumerator)info.Invoke(this, null));
    }
}
