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

[RequireComponent (typeof (CharacterController))]
public class move : MonoBehaviour {

    public float rangeOfWalk;
    public float speed;
    public float rotationSpeed;
    private Vector3 initialPosition;
    private Vector3 startingPosition;
    private Vector3 endingPosition;
    private Vector3 normalizedPosition;
    private float length;
	private float startTime;
	private bool isMoving;
    private Quaternion lookRotation;
    private Vector3 _direction;
    CharacterController controller;

	// Use this for initialization
	void Start () {
		speed = 5.0f * GameInfo.getCrowdSpeed ();
        rangeOfWalk = 5.0f;
		startingPosition = transform.position;
		initialPosition = transform.position;
        normalizedPosition = new Vector3(0, 0, 0);
        isMoving = false;
        controller = GetComponent<CharacterController>();
        length = 0.0f;; 
	}

	void Update()
	{
        if (isMoving == false) {
            Vector3 randomPointInArea = new Vector3 (Random.Range (-normalizedPosition.x - rangeOfWalk, rangeOfWalk - normalizedPosition.x),
                    transform.position.y,
                    Random.Range (-normalizedPosition.z - rangeOfWalk, rangeOfWalk - normalizedPosition.z));
            normalizedPosition.Set(randomPointInArea.x, 0, randomPointInArea.z);
            endingPosition = startingPosition + normalizedPosition;
            isMoving = true;
            startTime = Time.time;
            length = Vector3.Distance(transform.position, endingPosition);
            _direction = (endingPosition - transform.position);
            _direction.Normalize();
            lookRotation = Quaternion.LookRotation(_direction);
            transform.rotation = lookRotation;
            transform.Rotate(0, 90, 0);
        }
        //Debug.Log(length);
        //float journey = ((Time.time - startTime) * speed)/length;
        //transform.position = Vector3.Lerp(transform.position, endingPosition, journey);
        transform.position = Vector3.MoveTowards(transform.position, endingPosition, speed * Time.deltaTime);
        if (transform.position == endingPosition) {
            isMoving = false;
        }

	}
}
