using UnityEngine;
using System.Collections;

public class WizzardAnimScript : MonoBehaviour {
	public Transform hat, head, body, robeend, model;
	float gaitPhase = 0;

	Vector3 hatPos, headPos, bodyPos, robeEndPos;

	public static Vector3 velocity {get; set;}
	public static bool bOnGround {get; set;}
	public static bool bCasting {get; set;}

	bool bWasOnGround;
	float jumpTimer;

	void Awake() {
		//get default positions of all parts
		hatPos = hat.transform.localPosition;
		headPos = head.transform.localPosition;
		bodyPos = body.transform.localPosition;
		robeEndPos = robeend.transform.localPosition;
		bWasOnGround = true;
	}

	void Update() {
		if (!bOnGround && bWasOnGround)
		{
			jumpTimer = 0.4f;
		}
		else if (jumpTimer > 0)
		{
			jumpTimer -= Time.deltaTime;
			if (jumpTimer < 0) jumpTimer = 0;
		}

		UpdateModelRotation();
		UpdateModelAnimation();

		bWasOnGround = bOnGround;
	}

	public void UpdateModelRotation()
	{
		//manage model rotation
		if (velocity.x > 0) //moving to right - model should turn to right
		{
			Vector3 v = model.localEulerAngles;
			if (v.z > 180) v.z -= 360;
			else if (v.z < -180) v.z += 360;
			if (v.z < 90)
			{
				v.z += 360 * Time.deltaTime;
				if (v.z > 90) v.z = 90;
			}
			model.localEulerAngles = v;
		}
		else if (velocity.x < 0) //turn to left
		{
			Vector3 v = model.localEulerAngles;
			if (v.z > 180) v.z -= 360;
			else if (v.z < -180) v.z += 360;
			if (v.z > -90)
			{
				v.z -= 360 * Time.deltaTime;
				if (v.z < -90) v.z = -90;
			}
			model.localEulerAngles = v;
		}
	}
	public void UpdateModelAnimation() 
	{
		float vx = Mathf.Abs(velocity.x);
		if ((vx > 0.1f)&&(bOnGround))
			gaitPhase += Time.deltaTime * vx * 2f;
		else
			gaitPhase += Time.deltaTime * (bCasting?2f:0.2f);
		if (gaitPhase > 1) gaitPhase -= 2;
		float dispMult = 1 - (gaitPhase * gaitPhase);
		if (bCasting)
		{
			robeend.transform.localPosition = robeEndPos;
			body.transform.localPosition = bodyPos + new Vector3(0,0,(dispMult*0.2f)-0.15f);
			robeend.localEulerAngles = new Vector3(-3f+dispMult*-4f,0,0);
			body.localEulerAngles = new Vector3(-3f+dispMult*-4f,0,0);
			head.localEulerAngles = new Vector3(-3f+dispMult*-4f,0,0);
			hat.localEulerAngles = new Vector3(-3f+dispMult*-4f,0,0);
		}
		else
		{
			robeend.transform.localPosition = robeEndPos + new Vector3(0,0,-jumpTimer*0.5f);
			body.transform.localPosition = bodyPos + new Vector3(0,0,(jumpTimer*0.5f)+(dispMult*-0.1f));
			robeend.localEulerAngles = new Vector3(vx*2,0,0);
			body.localEulerAngles = new Vector3(vx*1.5f,0,0);
			head.localEulerAngles = new Vector3(vx*-2f,0,0);
			hat.localEulerAngles = new Vector3((vx+3*dispMult)*-2f,0,0);
		}

	}
}
