using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class GroupList
{
    public List<EnemyType> groupSpawn;
    public float triggerTime;
}
[CreateAssetMenu(menuName = "Gather And Defend/Levels/WaveConfig")]
public class WaveConfig : ScriptableObject
{

    [SerializeField]
    private List<EnemyType> _constantSpawn = new List<EnemyType>();
    [SerializeField]
    private List<GroupList> _nestedGroupSpawn = new List<GroupList>();
    [SerializeField]
    private float _gameDuration = 1;
    private List<GameObject> _constraintList = new List<GameObject>();  //List of depleted enemies
    private float _enemySpawndOnStart = 0;
    private int _enemySum = 0;
    public List<EnemyType> ConstantSpawn
    {
        get
        {
            return _constantSpawn;
        }
    }

    /**
     * Contains every list of enemy groups
     */
    public List<GroupList> NestedGroupSpawn
    {
        get
        {
            return _nestedGroupSpawn;
        }
    }
    public float Interval
    {
        get {
            float interval = _gameDuration * 60.0f / (_enemySum > 0 ? _enemySum.ToFloat() : SumCount());
            return interval;
        }
    }
    public float GameDuration { get { return _gameDuration; } }
    /**
     * Returns the updated game interval after adjusting to enemies spawned at the start
     */
    public float GetUpdatedInterval()
    {
        _enemySpawndOnStart++;
        float interval = Mathf.Max(_gameDuration * 60.0f / (_enemySum - _enemySpawndOnStart).ToFloat(), 0);
        return interval;
    }

    /**
     * Returns a random enemy among the constantSpawn list
     * Called when assigning a new enemy to a spawner
     * <param name="constraint"> When given, ensures that assigned enemy hasn't depleted </param>
     */
    public EnemyType GetRandomSpawn(GameObject constraint = null)
    {
        if (_constantSpawn.Count == 1)
        {
            return _constantSpawn[0];
        } else if (constraint != null)
        {
            if (!_constraintList.Contains(constraint))
            {
                _constraintList.Add(constraint);
            }
            if (_constraintList.Count < _constantSpawn.Count)
            {
                EnemyType randomEnemy;
                do
                {
                    randomEnemy =  _constantSpawn[Random.Range(0, _constantSpawn.Count)];
                } while (_constraintList.Contains(randomEnemy.GetEnemyObject()));
                return randomEnemy;
            } else
            {
                return null;
            }
        }
        return _constantSpawn[Random.Range(0, _constantSpawn.Count)];
    }

    /**
     * Returns the count of enemies to spawn
     */
    private float SumCount()
    {
        foreach (EnemyType enemy in _constantSpawn)
        {
            _enemySum += enemy.Count;
        }
        return _enemySum.ToFloat();
    }
}
