using System.Collections;
using UnityEngine;
using matnesis.TeaTime;

public class CameraShake : MonoBehaviour 
{
	public float duration = 0.5f;
	public float magnitude = 0.4f;
	public float speed = 2;

	private TeaTime shake;

 	void Start() 
	{
		shake = this.tt().Pause();

		{
			Vector3 originalCamPos = transform.position;
	
			shake.Add(() => 
				{
					originalCamPos = transform.position;
				}).Loop (duration, (ttHandler t) => 
				{
				float randomStart = Random.Range (-1000.0f, 1000.0f);	

				// We want to reduce the shake from full power to 0 starting half way through
				float damper = 1.0f - Mathf.Clamp (2.0f * t.t - 1.0f, 0.0f, 1.0f);

				// Calculate the noise parameter starting randomly and going as fast as speed allows
				float alpha = randomStart + speed * t.t;

				// map noise to [-1, 1]
				float x = Util.Noise.GetNoise (alpha, 0.0f, 0.0f) * 2.0f - 1.0f;
				float y = Util.Noise.GetNoise (0.0f, alpha, 0.0f) * 2.0f - 1.0f;

				x *= magnitude * damper;
				y *= magnitude * damper;

			Camera.main.transform.position = new Vector3 (originalCamPos.x + x, originalCamPos.y + y, originalCamPos.z);
			}).Add (() => 
			{
				Camera.main.transform.position = originalCamPos;
			}).Immutable ();
		}
	}

	void Update ()
	{
		if(Input.GetKeyDown(KeyCode.L))
		{
			Shake ();
		}
	}

	public void Shake ()
	{
		shake.Play ().Forward ();
	}
}
