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


public class BlockMaster : MonoBehaviour
{

	[Serializable]
	public struct DifficultyLevel
	{
		public float WaveTime;
		public Transform BlockPrefab;
		public int WaveCountToAdvance;
		public float TimeDecay;
	}

	public List<DifficultyLevel> Levels;
	public FXTrigger SpawnFX;
	private int wavesDoneThisLevel;

	private DifficultyLevel level;
	public int levelIdx;  // Public just to see in inspector for debug

	//public Transform BlockPrefab;

	//public float WaveIntervalTime = 10f;

	public float SlideTime = 0.65f;
	public float LineIntervalTime = 0.65f;

	public bool AllowTestWaves = true;
	private float side = -1;
	private float busyUntil;

	private List<Block> blocksToSlide;

    void Start()
    {
		level = Levels[0];
		Invoke("SpawnWave", level.WaveTime + 5f);
	}

    void Update()
    {
        if(AllowTestWaves && Input.GetKeyDown(KeyCode.Z) && Time.time > busyUntil)
		{
			SpawnWave();
		}
    }

	private void MoveToNextLevel()
	{
		if (levelIdx + 1 >= Levels.Count)
			return;

		levelIdx++;
		level = Levels[levelIdx];
		wavesDoneThisLevel = 0;
	}

	private void SpawnWave()
	{
		Invoke("DoSpawnFX", 0.075f);

		busyUntil = Time.time + 1f + LineIntervalTime * 5f;
		Transform prefab = level.BlockPrefab;

		for (int x = -2; x <= 2; x++)
		{
			float wavex = (float)x * side;
			Transform newblock = Instantiate(prefab);
			newblock.position = new Vector3(wavex, -5f, 0f);
			ShoveLine(wavex, LineIntervalTime * (x + 2));
		}

		side *= -1f;

		wavesDoneThisLevel++;
		if (ReadyForNextWave())
		{
			MoveToNextLevel();
		}

		Invoke("SpawnWave", Mathf.Max(3.25f, level.WaveTime - level.TimeDecay * wavesDoneThisLevel));
	}

	private void DoSpawnFX()
	{
		SpawnFX.Trigger(transform);
	}

	private bool ReadyForNextWave()
	{
		return level.WaveCountToAdvance > -1 && wavesDoneThisLevel > level.WaveCountToAdvance;
	}

	private void ShoveLine(float x, float delay)
	{

		Collider2D[] hits = Physics2D.OverlapBoxAll(new Vector2(x, 0), new Vector2(0.25f, 10f), 0);
		
		foreach(Collider2D hit in hits)
		{
			Block b = hit.transform.GetComponent<Block>();
			if(b != null)
			{
				b.transform.DOMoveY(b.transform.position.y + 1, SlideTime).SetEase(Ease.InOutCubic).SetDelay(delay);
			}
		}
	}
}
