using UnityEngine;
using System.Collections;

public class RotationController : MonoBehaviour
{
	protected Transform _transform;
	protected float _rotation;
	protected float _targetRotation;
	protected float _rotationSpeed;
	protected bool _isEnabled;
	
	public Transform GetTransform() { return _transform; }
	public float GetRotation() { return _rotation; }
	public float GetTargetRotation() { return _targetRotation; }
	public void SetRotationSpeed(float rotationSpeed) { _rotationSpeed = rotationSpeed; }
	public void SetIsEnabled(bool isEnabled) { _isEnabled = isEnabled; }
	
	public virtual void Awake()
	{
		_transform = gameObject.transform;
		_rotation = 0;
		_targetRotation = 0.0f;
		_rotationSpeed = 10.0f;
	}
	
	public void Update ()
	{
		if(!_isEnabled)
			return;
		
		if(Mathf.Abs(_rotation - _targetRotation) < 1.0f)
			setRotation(_targetRotation);
		
		if(_rotation != _targetRotation)
		{
			if(_rotation > 0 && _targetRotation <= 0)
			{
				if(_targetRotation < (-180.0f + _rotation))
					_targetRotation = 360.0f + _targetRotation;
			}
			else if(_rotation <= 0 && _targetRotation > 0)
			{
				if(_targetRotation > (180.0f - Mathf.Abs(_rotation)))
					_targetRotation = -360.0f + _targetRotation;
			}
			
			setRotation(Mathf.Lerp(_rotation, _targetRotation, _rotationSpeed * Time.deltaTime));
			
			if(_rotation > 180.0f)
			{
				_rotation = -180.0f + (_rotation - 180.0f);
				
//				if(_targetRotation > 180.0f)
//					_targetRotation = (-180.0f + (_targetRotation - 180.0f));
			}
			else if(_rotation < -180.0f)
			{
				_rotation = 180.0f - (_rotation + 180.0f);
				
//				if(_targetRotation < -180.0f)
//					_targetRotation = (180.0f - (_targetRotation + 180.0f));
			}
		}
	}
	
	public void setRotation(float degrees)
	{
		_rotation = degrees;
		_transform.rotation = Quaternion.identity;
		_transform.RotateAround(Vector3.forward, degrees * Mathf.Deg2Rad);
	}
	
	public void setTargetRotation(float targetRotation)
	{
		_targetRotation = targetRotation;	
	}
}





















