using UnityEngine;
using ScrambleKit;
using Shapes;


public class BigAir : MonoBehaviour
{
	public FXTrigger CelebrationFX;

	public float goalHeight = 20f;
	public float trackHeight = 14f;
	public float disappearHeight = 6f;

	public Transform smashBall;
	public bool debugLog = true;

	enum BAState
	{
		Idle,
		Tracking,
		Celebrating,
		Achieved
	}
	private BAState state;
	private float celebrateUntil;
	private Vector3 celebratePos;
	private float bestHeight;
	private Vector3 bestDisplayPos;

	public bool isAchieved()
	{
		return (state == BAState.Celebrating || state == BAState.Achieved);
	}

	void FixedUpdate()
	{
		switch (state)
		{
			case BAState.Idle:
				if (AtTrackingLevel())
				{
					SetState(BAState.Tracking);
				}
				break;
			case BAState.Tracking:
				if (AtGoal())
				{
					celebrateUntil = 4f + Time.time;
					celebratePos = GetDisplayPos() * 0.8f;
					CelebrationFX.Trigger(smashBall);
					SetState(BAState.Celebrating);
				}
				else if (BelowDisppearLevel())
				{
					bestHeight = 0f;
					SetState(BAState.Idle);
				}
				break;
			case BAState.Celebrating:
				if (Time.time > celebrateUntil)
				{
					SetState(BAState.Achieved);
				}
				break;
		}
	}

	private bool AtTrackingLevel()
	{
		return smashBall.position.y >= trackHeight;
	}

	private bool BelowDisppearLevel()
	{
		return smashBall.position.y <= disappearHeight;
	}

	private bool AtGoal()
	{
		return smashBall.position.y >= goalHeight;
	}

	private void SetState(BAState newState)
	{
		if (debugLog)
			Debug.Log("BigAir Achievement moving from " + state + " to " + newState);

		state = newState;
	}


	public void ImmediateDraw()
	{
		switch (state)
		{
			case BAState.Tracking:
				bool isBest = bestHeight <= smashBall.position.y;

				if (isBest)
				{
					bestHeight = smashBall.position.y;
					bestDisplayPos = GetDisplayPos();
				}

				Vector3 p = bestDisplayPos;
				Vector3 t = p + 2.4f*Vector3.left;
				Draw.Triangle(
					t + .35f * Vector3.left + 0.35f * Vector3.down,
					t + .35f * Vector3.right + 0.35f * Vector3.down,
					t + 0.35f * Vector3.up,
					(isBest) ? Color.yellow : Color.white
				);

				string s = bestHeight.ToString("N1") + "/" + goalHeight.ToString("N0");
				Draw.Text(p, s, fontSize: 8, Color.white);
				break;
			case BAState.Celebrating:
				string celeb = "Completed!\nBig Air";
				Draw.Text(celebratePos, celeb, fontSize: 10, Color.white);
				break;
		}
	}

	private Vector3 GetDisplayPos()
	{
		float x = Mathf.Clamp(smashBall.position.x, -12, 9);
		float y = 14f;
		return new Vector3(x, y);
	}

}
