using UnityEngine;
using System.Collections;

public class GenieAnimScript : MonoBehaviour {
	public Transform model;
	public Transform[] leftArm, rightArm, tail;
	Vector3[] leftArmPositions, rightArmPositions, tailPositions;
	float gaitPhase = 0;
	
	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
		leftArmPositions = new Vector3[leftArm.Length];
		rightArmPositions = new Vector3[rightArm.Length];
		tailPositions = new Vector3[tail.Length];
		for (int i=0;i<leftArm.Length;++i)
		{
			leftArmPositions[i] = leftArm[i].position;
		}
		for (int i=0;i<rightArm.Length;++i)
		{
			rightArmPositions[i] = rightArm[i].position;
		}
		for (int i=0;i<tail.Length;++i)
		{
			tailPositions[i] = tail[i].position;
		}
		bWasOnGround = true;
	}

	// Update is called once per frame
	void Update () {
		
		if (!bOnGround && bWasOnGround)
		{
			jumpTimer = 0.8f;
		}
		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;
			}
			v.y = velocity.x * 2;
			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;
			}
			v.y = velocity.x * 2;
			model.localEulerAngles = v;
		}
	}
	public void UpdateModelAnimation() 
	{
		float vx = Mathf.Abs(velocity.x);
		gaitPhase += Time.deltaTime * (bCasting?2f:0.7f);
		if (gaitPhase > 1) gaitPhase -= 2;
		float dispMult = Mathf.Sin (gaitPhase * Mathf.PI);
		if (bCasting)
		{
		}
		else
		{
			foreach(Transform tf in tail)
			{
				tf.localEulerAngles = new Vector3(dispMult*5 + (vx*3),0,0);
			}
			foreach(Transform tf in leftArm)
			{
				tf.localEulerAngles = new Vector3(dispMult*5 + (vx*3),0,0);
			}
			foreach(Transform tf in rightArm)
			{
				tf.localEulerAngles = new Vector3(dispMult*5 + (vx*3),0,0);
			}
		}
		
	}
}
