using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using DG.Tweening;
using ScrambleKit;

public class SecondHand : MonoBehaviour
{
	public float TickInterval = 1f;
	public float RotateInterval = 6f;
	public float TickMoveTime = 0.05f;

	public FXTrigger TickSmallFX;
	public FXTrigger TickBigFX;

	public List<PlatformPop> Platforms;
	public List<Transform> PlatformNexts;

	private float nextSwitchTime;
	private Vector3 tickRotation;
	private int seconds = 0;
	private bool gameIsEnding = false;


	private void Start()
	{
		tickRotation = new Vector3(0, 0, RotateInterval);
		nextSwitchTime = Time.fixedTime + TickInterval;
	}

	void FixedUpdate()
    {
		if(Scoreboard.instance == null)
		{
			DoTitleScrenTick();
			return;
		}

		if (gameIsEnding || Scoreboard.instance.timesUp)
			return;

		if (Time.fixedTime < nextSwitchTime)
			return;

		if(Scoreboard.instance.playerDied)
		{
			EndTheGame();
			return;
		}

		seconds++;
		CallPops();
		transform.DORotate(transform.eulerAngles - tickRotation, TickMoveTime).SetEase(Ease.OutBack);
		DOVirtual.DelayedCall(0.5f * TickMoveTime, TickFX, true);
		nextSwitchTime = Time.fixedTime + TickInterval;

		if (seconds >= 56)
		{
			Scoreboard.instance.noMoreBalloons = true;
		}
		if (seconds >= 60)
		{
			Scoreboard.instance.timesUp = true;
		}
	}

	private void DoTitleScrenTick()
	{
		if (Time.fixedTime >= nextSwitchTime)
		{
			seconds++;
			transform.DORotate(transform.eulerAngles - tickRotation, TickMoveTime).SetEase(Ease.OutBack);
			DOVirtual.DelayedCall(0.35f * TickMoveTime, TickFX, true);
			nextSwitchTime = Time.fixedTime + TickInterval;
		}
	}

	private void EndTheGame()
	{
		gameIsEnding = true;
		transform.DORotate(Vector3.zero, 0.7f).OnComplete(ReloadLevel);
	}

	private void ReloadLevel()
	{
		DOTween.KillAll();
		SceneManager.LoadScene(SceneManager.GetActiveScene().name);
	}

	private void CallPops()
	{
		for (int i=0; i<Platforms.Count; i++)
		{
			PlatformPop plat = Platforms[i];
			Transform next = PlatformNexts[i];

			Vector3 moveDelta = next.position - plat.transform.position;
			plat.PopPlayer(moveDelta);			
		}
	}

	private void TickFX()
	{
		if (seconds % 10 == 0)
			TickBigFX.Trigger(transform);
		else
			TickSmallFX.Trigger(transform);
	}

}
