using UnityEngine;

[DisallowMultipleComponent]
public class Griddy : MonoBehaviour
{

    private static Griddy instance;

    public static Griddy Instance
    {
        get
        {
            return instance;
        }
    }

    public Griddy()
    {
        //Debug.Log("new Grid");
        if(instance == null)
            instance = this;
    }

    public int gridWidth = 32;

    public int gridHeight = 18;

    public int cellWidth = 100;

    public int cellHeight = 100;

    public Color gizmoColor = Color.white;

    public bool alwaysDraw = true;

    private Cell[][] cells;

    void OnDrawGizmos()
    {
        if(alwaysDraw)
        {
            DrawGizmos();
        }
    }

    void OnDrawGizmosSelected()
    {
        if(!alwaysDraw)
        {
            DrawGizmos();
        }
    }

    private void DrawGizmos()
    {
        Gizmos.color = gizmoColor;

        for (int i = 0; i < gridWidth + 1; i++)
        {
            Gizmos.DrawLine(new Vector3(i * cellWidth, 0),
                new Vector3(i * cellWidth, gridHeight * cellHeight));
        }

        for (int j = 0; j < gridHeight + 1; j++)
        {
            Gizmos.DrawLine(new Vector3(0, j * cellHeight),
                new Vector3(gridWidth * cellWidth, j * cellHeight));
        }
    }

    void Awake()
    {
        cells = new Cell[gridWidth][];
        for (int i = 0; i < cells.Length; i++)
        {
            cells[i] = new Cell[gridHeight];
            for (int j = 0; j < cells[i].Length; j++)
            {
                cells[i][j] = new Cell();
            }
        }

        //Debug.Log("Cells initialized grmblmkblmlb" + cells);
    }

    public void AddWaveOnCells(WaveInstance waveInstance)
    {
        for(int i=0; i<waveInstance.zone.width; i++)
        {
            for(int j=0; j<waveInstance.zone.height; j++)
            {
                int x = i + waveInstance.zone.x;
                int y = j + waveInstance.zone.y;
                if (x >= 0 && y >= 0 && x < gridWidth && y <gridHeight)
                {
                    cells[x][y].AddWave(waveInstance.wave.type);
                }
            }
        }
    }

    public Cell GetCell(int x, int y)
    {
        if(cells == null)
        {
            Debug.Log("Cells are null !");
        }
        return cells[x][y];
    }

}
