using UnityEngine;
using ScrambleKit;
using Shapes;

public class DoubleCenter : MonoBehaviour
{
	public FXTrigger CelebrationFX;

	public float timeLimit = 1.4f;
	public Transform smashBall;
	public Transform anchor;
	public float touchDist = 1f;
	public bool debugLog = true;

	enum DCState
	{
		Idle,
		InFirstTouch,
		WaitingForSecondTouch,
		Celebrating,
		Achieved
	}
	private DCState state;
	private float getSecondBefore;
	private float celebrateUntil;

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

	void FixedUpdate()
    {
        switch(state)
		{
			case DCState.Idle:
				if(IsTouching())
				{
					SetState(DCState.InFirstTouch);
				}
				break;
			case DCState.InFirstTouch:
				if (!IsTouching())
				{
					getSecondBefore = timeLimit + Time.time;
					SetState(DCState.WaitingForSecondTouch);
				}
				break;
			case DCState.WaitingForSecondTouch:
				if(IsTouching())
				{
					celebrateUntil = 4f + Time.time;
					CelebrationFX.Trigger(anchor);
					SetState(DCState.Celebrating);
				}
				else if (Time.time > getSecondBefore)
				{
					SetState(DCState.Idle);
				}
				break;
			case DCState.Celebrating:
				if (Time.time > celebrateUntil)
				{
					SetState(DCState.Achieved);
				}
				break;
		}
    }

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

		state = newState;
	}

	private bool IsTouching()
	{
		return (smashBall.position - anchor.position).magnitude <= 1.0f;
	}


	public void ImmediateDraw()
	{
		switch (state)
		{
			case DCState.InFirstTouch:
				DisplayTimeLimit(timeLimit.ToString("N2"));
				Draw.Disc(anchor.position, 0.5f, Color.yellow);
				break;
			case DCState.WaitingForSecondTouch:
				DisplayTimeLimit(Mathf.Max(0,getSecondBefore-Time.time).ToString("N2"));
				break;
			case DCState.Celebrating:
				string s = "Completed!\nDouble-Center";
				Draw.Text(anchor.position + 3f * Vector3.up, s, fontSize: 10, Color.white);
				break;
		}
	}

	private void DisplayTimeLimit(string s)
	{
		Draw.Text(anchor.position + 2f * Vector3.up, s, fontSize: 8, Color.white);
	}
}
