using System;
using System.Collections;
using System.Collections.Generic;
//using System.Linq;

//using UnityEditor;
using UnityEngine;
//using UnityEngine.UI;
//using Uhity.Entities;

using URD = UnityEngine.Random;

public class Beaver : MonoBehaviour {
	
	// public Rigidbody rbody;
	
	public CharacterController controller;
	public Animator anim;
	
	public Vector3 targetPoint;
	
	public Vector3 velocity;
	
	public void Eat() {
		anim.CrossFade("eat", 0.25f);
	}
	
	public void Hair() {
		anim.CrossFade("idle_2", 0.25f);
	}
	
	public void Stop() {
		targetPoint = transform.position;
		velocity = Vector3.zero;
	}
	
	private IEnumerator AnimUpdate() {
		
		while(true) {
		
			if(velocity.magnitude > 0.25f)
				yield return StartCoroutine(Move());
			else
				yield return StartCoroutine(Idle());
			
			
			yield return null;
		}
		
	}
	
	private IEnumerator Move() {
		
		anim.CrossFade("walk", 0.25f);
		
		while(velocity.magnitude > 0.25f) {
			
			
			yield return null;
		}
	}
	
	private IEnumerator Idle() {
		
		anim.CrossFade("idle_0", 0.25f);
		
		var enter = Time.time;
		var interval = URD.Range(5f,10f);
		
		while(velocity.magnitude < 0.25f) {
			
			if(Time.time - enter > interval) {
				yield return StartCoroutine(RandIdle());
				enter = Time.time;
				interval = URD.Range(2.5f,10);
				anim.CrossFade("idle_0", 0.25f);
			}
			
			yield return null;
		}
	}
	
	private IEnumerator RandIdle() {
		
		var randTime = URD.Range(1.25f, 4f);
		
		anim.CrossFade(URD.value > 0.45f ? "idle_1" : "idle_2", 0.25f);
		
		var randDir = new Vector3(URD.Range(-1,1), 0, URD.Range(-1,1));
		
		var t = URD.value;
		
		while(velocity.magnitude < 0.25f && randTime > 0) {
			
			t -= Time.deltaTime;
			
			if(t>0)
				Move(randDir);
			else
				Move(Vector3.zero);
			
			randTime -= Time.deltaTime;
			
			yield return null;
		}
	}
	
	// Start is called before the first frame update
	void Start() {
		targetPoint = transform.position;
		
		StartCoroutine(AnimUpdate());
	}
	
	
	// Update is called once per frame
	void Update() {
		var disp = targetPoint - transform.position;
		
		if( disp.magnitude > 0.5f)
			Move(disp);
		else
			Move(Vector3.zero);
	}
	
	private void Move(Vector3 disp) {
		var moveSpeed = Vector3.ClampMagnitude(disp*2f, 1.5f);
		
		var v = Vector3.Lerp(velocity, moveSpeed, 6*Time.deltaTime);
		
		v.y = -5f;
		controller.Move(v * Time.deltaTime);
		
		// moveSpeed.y = rbody.velocity.y;
		// rbody.velocity = Vector3.Lerp(rbody.velocity, moveSpeed, 12*0.02f);
		// rbody.velocity = moveSpeed;
		
		// velocity = rbody.velocity;
		velocity = v;
		velocity.y = 0;
		
		if(disp.magnitude > 0.1f) {
			var dir = disp;
			dir.y = 0;
			var r = Quaternion.LookRotation(dir.normalized);
			transform.rotation = Quaternion.Lerp(transform.rotation, r, 6 * Time.deltaTime);
		}
		
	}
}
