using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemiesWaves : MonoBehaviour {

    [SerializeField]private float baseSpawnTime;
    private float actualSpawnTime;

    [SerializeField]private int spawnAmountToDrecreaseTime;
    [SerializeField]private AnimationCurve spawnTimeCurve;
    [SerializeField]private AudioSource enemyMovingSound;

    private int spawnedAmount;
    private float spawnTimer;

    private const float TIME_STEPS = 0.1f;
	
	// Update is called once per frame
	void Update () {
        CountSpawnTimer();
	}

    private void CountSpawnTimer ()
    {
        spawnTimer += Time.deltaTime;

        if (spawnTimer >= spawnTimeCurve.Evaluate(actualSpawnTime / baseSpawnTime) * baseSpawnTime)
        {
            spawnTimer = 0f;

            if (!enemyMovingSound.isPlaying)
            {
                enemyMovingSound.Play();
            }

            GameObject enemy = ObjectPooler.Instance.GetPooledObject(PoolObjectTags.Enemy.ToString());

            float xPos = Random.value > 0.5f ? -Globals.OutsideScreenXPos : Globals.OutsideScreenXPos;

            Vector2 enemyPosition = new Vector2(xPos, Random.Range(Globals.MinYSpawnPos, Globals.MaxYSpawnPos));
            enemy.transform.position = enemyPosition;
            enemy.SetActive(true);

            AddSpawnedEnemyCount();
        }
    }

    private void AddSpawnedEnemyCount ()
    {
        spawnedAmount++;

        if (spawnedAmount >= spawnAmountToDrecreaseTime)
        {
            spawnedAmount = 0;
            actualSpawnTime += TIME_STEPS;
        }
    }

    public void StartSpawn ()
    {
        enabled = true;
    }
}
