using UnityEngine;
using System.Collections;

namespace com.deeperbeige.lib.components
{
	internal class AccelerometerShift : MonoBehaviour
	{
		public float   filterFactor   = 1.0f;
		public Vector3 movementAmount = new Vector3(1.0f, 1.0f, 1.0f);  // In world units
		public Vector3 rotationAmount = new Vector3(0.0f, 0.0f, 0.0f);  // In degrees
		
		private Vector3 origPos;
		private Vector3 origEulers;
		private Vector3 filteredAcceleration = Vector3.zero;
		
		void Start ()
		{
			origPos              = transform.localPosition;
			origEulers           = transform.localEulerAngles;
			filteredAcceleration = Input.acceleration;
		}
		
		void Update ()
		{
			filteredAcceleration = Vector3.Lerp(filteredAcceleration, Input.acceleration, Time.deltaTime * filterFactor);
			
			// Deliberately mixes coordinates for position to better match acclerometer movement
			if (movementAmount != Vector3.zero)
			{
				transform.localPosition = origPos + new Vector3(movementAmount.x * filteredAcceleration.x,
				                                                movementAmount.y * filteredAcceleration.z,
				                                                movementAmount.z * filteredAcceleration.y);
			}
			
			// Deliberately mixes coordinates for rotation to better match acclerometer movement
			if (rotationAmount != Vector3.zero)
			{
				transform.localEulerAngles = origEulers + new Vector3(rotationAmount.x * -filteredAcceleration.y,
				                                                      rotationAmount.y * -filteredAcceleration.z,
				                                                      rotationAmount.z * -filteredAcceleration.x);
			}
		}
	}
}
