using UnityEngine;

public class Joe : MonoBehaviour
{
	// ********************************************************************************
	// Constants
	enum JoeState
	{
		Neutral,
		Laugh,
		Probing
	}

	const float GoInDuration = 1.0f;
	readonly Vector3 HandInPosition = new Vector3(-0.28f, -2.4f, 0.0f);
	readonly Vector3 HandOutPosition = new Vector3(-0.48f, -7.35f, 0.0f);

	// ********************************************************************************
	// Members
	JoeState _state = JoeState.Neutral;
	float _handGoTimer;

	Vector3 _handPosition = Vector3.zero;
	Vector3 _handRotation = Vector3.zero;

	// ********************************************************************************
	// Properties
	public SpriteRenderer Renderer;
	public SpriteRenderer OverlayRenderer;
	public Sprite FrameNeutral;
	public Sprite FrameLaugh;
	public Sprite FrameMess;
	
	public Probe Probe;

	public SpriteRenderer HandRenderer;
	
	// ********************************************************************************
	// Unity messages
	void Start()
    {
		_handGoTimer = 0.0f;
	}

    void Update()
    {
		if (_state == JoeState.Laugh)
		{
			Renderer.sprite = FrameLaugh;
			OverlayRenderer.enabled = false;
			HandRenderer.enabled = false;
			//_handPosition = HandOutPosition;
			//_handRotation = Vector3.zero;
			_handGoTimer = 1.0f;
		}
		else if (_state == JoeState.Probing)
		{
			Renderer.sprite = FrameMess;
			OverlayRenderer.enabled = true;
			HandRenderer.enabled = true;

			if (_handGoTimer < GoInDuration)
			{
				_handPosition = Vector3.Lerp(HandOutPosition, HandInPosition, _handGoTimer);
				_handRotation = Vector3.zero;
				_handGoTimer += Time.deltaTime;
			}
			else
			{
				var targetPosition = HandInPosition + new Vector3(0.0f, Probe.Movement.y * 0.5f, 0.0f);
				var linearVelocity = Vector3.zero;
				_handPosition = Vector3.SmoothDamp(_handPosition, targetPosition, ref linearVelocity, 0.02f);

				var targetRotation = new Vector3(0.0f, 0.0f, Probe.Movement.x * -20.0f);
				var angularVelociy = Vector3.zero;
				_handRotation = Vector3.SmoothDamp(_handRotation, targetRotation, ref angularVelociy, 0.05f);
			}
		}
		else
		{
			Renderer.sprite = FrameNeutral;
			OverlayRenderer.enabled = false;
			HandRenderer.enabled = true;
			_handPosition = HandOutPosition;
			_handRotation = Vector3.zero;
			_handGoTimer = 0.0f;
		}

		HandRenderer.gameObject.transform.localPosition = _handPosition;
		HandRenderer.gameObject.transform.rotation = Quaternion.Euler(_handRotation);
	}

	// ********************************************************************************
	// Gameplay events
	public void Reset()
	{
		_state = JoeState.Neutral;
	}

	public void StartProbing()
	{
		_state = JoeState.Probing;
	}

	public void Laugh()
	{
		_state = JoeState.Laugh;
	}
}
