using UnityEngine;
using ScrambleKit;

public class Balloon : MonoBehaviour
{
	public float RiseSpeed = 3f;
	public float WiggleWidth = 0.15f;
	public float WiggleRateHz = 1.2f;
	public float DeathAboveHeight = 8.5f;

	public FXTrigger ScorePopFX;
	public FXTrigger FailPopFX;

	public enum BalloonColor
	{
		Golden,
		Blue,
		Purple
	};
	public BalloonColor color;

	private float myRiseSpeed;
	private float myWiggleWidth;
	private float myWiggleRateHz;
	private float myWiggleTimeOffset;
	private float origX;

	// gameover dramatics:
	private bool crashing;
	private float crashSpeed;

	private Boostable playerBoost;
	private bool alreadyPopped = false;

	void FixedUpdate()
    {
		if (Scoreboard.instance != null && Scoreboard.instance.playerDied)
		{
			CrashUpdate();
			return;
		}

		float rise = myRiseSpeed * Time.fixedDeltaTime;
		float phase = Mathf.Sin((Time.fixedTime + myWiggleTimeOffset) * myWiggleRateHz * 2f * Mathf.PI);
		float wiggle = phase * myWiggleWidth;

		Vector3 p = transform.position;
		transform.position = new Vector3(origX + wiggle, p.y + rise, 0);

		if(transform.position.y > DeathAboveHeight && !alreadyPopped)
		{
			FailPopFX.Trigger(transform);
			alreadyPopped = true;
			Destroy(gameObject);
		}
	}

	void CrashUpdate()
	{
		if (!crashing)
		{
			crashing = true;
			transform.eulerAngles = new Vector3(0, 0, -180);
			crashSpeed = -2f * RiseSpeed;
		}

		float phase = Mathf.Sin(10f * (Time.fixedTime + myWiggleTimeOffset) * myWiggleRateHz * 2f * Mathf.PI);
		float wiggle = .1f * phase * myWiggleWidth;

		Vector3 p = transform.position;
		transform.position = new Vector3(origX + wiggle, p.y + crashSpeed * Time.fixedDeltaTime, 0);
		crashSpeed -= 20f * Time.fixedDeltaTime;
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if (alreadyPopped) // balloons were popping twice and double-scoring!
			return;

		if (other.transform.root.gameObject.name.Equals("Player"))
		{
			alreadyPopped = true;
			ScorePopFX.Trigger(transform);
			Score();
			playerBoost.Boost();
			//Debug.Log(Time.fixedTime + ": Balloon calling boost");
			Destroy(gameObject);
		}
	}

	private void Score()
	{
		switch (color)
		{
			case BalloonColor.Golden:
				Scoreboard.instance.goldenBalloons++;
				break;
			case BalloonColor.Blue:
				Scoreboard.instance.blueBalloons++;
				break;
			case BalloonColor.Purple:
				Scoreboard.instance.purpleBalloons++;
				break;
		}
	}

	private void Start()
	{
		if(Player.instance != null)  // no player on title screen
			playerBoost = Player.instance.GetComponent<Boostable>();

		origX = transform.position.x;

		// variation on balloons prevents them visually feeling like one large unit of wallpaper background:
		myRiseSpeed = RiseSpeed * Random.Range(0.9f, 1.1f);  
		myWiggleWidth = WiggleWidth * Random.Range(0.9f, 1.1f);
		myWiggleRateHz = WiggleRateHz * Random.Range(0.8f, 1.2f);
		myWiggleTimeOffset = Random.Range(0, 2 * Mathf.PI);
	}
}
