using UnityEngine;
using ScrambleKit;
using Shapes;

public class LittleKing : MonoBehaviour
{
	public FXTrigger CelebrationFX;

	public float goalTime = 2f;

	public Transform smashBall;
	public Transform midJoint;
	public Transform anchor;
	public bool debugLog = true;

	enum LKState
	{
		Idle,
		Tracking,
		Celebrating,
		Achieved
	}
	private LKState state;

	private float stayUntil;
	private float celebrateUntil;
	private Vector3 celebratePos;

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

	void FixedUpdate()
	{
		switch (state)
		{
			case LKState.Idle:
				if (IsLittleOnTop())
				{
					stayUntil = goalTime + Time.time;
					SetState(LKState.Tracking);
				}
				break;
			case LKState.Tracking:
				if (Time.time >= stayUntil)
				{
					celebrateUntil = 4f + Time.time;
					celebratePos = GetDisplayPos() + 1.5f * Vector3.down;
					CelebrationFX.Trigger(midJoint);
					SetState(LKState.Celebrating);
				}
				else if (!IsLittleOnTop())
				{
					SetState(LKState.Idle);
				}
				break;
			case LKState.Celebrating:
				if (Time.time > celebrateUntil)
				{
					SetState(LKState.Achieved);
				}
				break;
		}
	}

	private bool IsLittleOnTop()
	{
		return midJoint.position.y > anchor.position.y && midJoint.position.y > smashBall.position.y;
	}

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

		state = newState;
	}


	public void ImmediateDraw()
	{
		switch (state)
		{
			case LKState.Tracking:
				Vector3 p = GetDisplayPos();
				Vector3 c = midJoint.position + 0.6f * Vector3.up;

				using (var crown = new PolygonPath())
				{
					// Clockwise
					// bottom corners
					crown.AddPoint(c + .3f * Vector3.right + 0.3f * Vector3.down);
					crown.AddPoint(c + .3f * Vector3.left  + 0.3f * Vector3.down);

					// left peak
					crown.AddPoint(c + .3f * Vector3.left + 0.3f * Vector3.up);

					// left trough
					crown.AddPoint(c + .15f * Vector3.left + 0.0f * Vector3.up);

					//center peak
					crown.AddPoint(c + 0.3f * Vector3.up);

					// right trough
					crown.AddPoint(c + .15f * Vector3.right + 0.0f * Vector3.up);

					// right peak
					crown.AddPoint(c + .3f * Vector3.right + 0.3f * Vector3.up);


					Draw.Polygon(crown, Color.yellow);						
				}

				float timeLeft = stayUntil - Time.time;
				if (timeLeft <= 1f)
				{
					string s = Mathf.Max(0, timeLeft).ToString("N2");
					Draw.Text(p, s, fontSize: 8, Color.white);
				}
				break;
			case LKState.Celebrating:
				string celeb = "Completed!\nLittle King";
				Draw.Text(celebratePos, celeb, fontSize: 10, Color.white);
				break;
		}
	}

	private Vector3 GetDisplayPos()
	{
		float x = midJoint.position.x + 1.5f;
		float y = Mathf.Min(15f, midJoint.position.y);
		return new Vector3(x, y);
	}

}
