using UnityEngine;
using System.Linq;
using System.Collections.Generic;
using Gamelogic.Grids2;

public class MonsterSpawner : MonoBehaviour 
{
    public Transform MonsterPrefab;  // replace with library of available monsters when we have multiple
    public int Interval = 5;
    public int WaveSize = 2;

    private int lastTurnChecked=-1;

    void Update()
    {
        if (!GameController.Instance.isGameRunning() || TurnBasedGameLoop.instance.TurnCount < 15)
            return;

        if (lastTurnChecked == TurnBasedGameLoop.instance.TurnCount)
            return;

        lastTurnChecked = TurnBasedGameLoop.instance.TurnCount;
        int useInterval = (ScoreBoard.instance.BabiesHatched < 4) ? Interval + 3 : Interval;        
        if (lastTurnChecked % useInterval == 0)
            SpawnWave();
    }

    private void SpawnWave()
    {
        int useWaveSize = Mathf.Min(6, WaveSize + (int)((float)ScoreBoard.instance.BabiesHatched / 8f));

        for(int i = 0; i<useWaveSize; i++)
        {
            GridPoint2 pos = GetSpawnLocation();
            if (pos == GridPoint2.None)
                return;

            SpawnActor.SpawnPrefabAt(MonsterPrefab, pos);
        }
    }

    private GridPoint2 GetSpawnLocation()
    {
        var valids = GameMap.instance.Grid.Points
            .Where(q => GameMap.Available(q))
            .Where(p => IsEdge(p))
            .ToList();

        if (valids.Count == 0)
            return GridPoint2.None;

        return ListHelper.DrawFromAtRandom(valids);
    }

    private bool IsEdge(GridPoint2 p)
    {
        var outsides = PointyHexPoint.GetOrthogonalNeighbors(p)
            .Where(q => !GameMap.Contains(q));

        return outsides.Count() != 0;
    }
}
