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

public class GridManager : MonoBehaviour {

    [SerializeField] int witdth;
    [SerializeField] int height;
    [SerializeField] Tile tilePrefab;
    [SerializeField] GameObject gridContainer;
    private CinemachineTargetGroup targetGroup;

    private Dictionary<Vector2, Tile> tiles;

    public void GenerateStartGrid() {
        tiles = new Dictionary<Vector2, Tile>();
        for (int x = 0; x < witdth; x++) {
            for (int y = 0; y < height; y++) {
                var tile = Instantiate(tilePrefab, new Vector3(x, y), Quaternion.identity);
                tile.name = $"Tile {x}, {y}";

                bool isOffset = (x % 2 == 0 && y % 2 != 0 || x % 2 != 0 && y % 2 == 0);
                tile.Init(isOffset);
                tiles[new Vector2(x, y)] = tile;
                getTargetGroup().AddMember(tile.transform, 1f, 0f);
                tile.transform.SetParent(gridContainer.transform);
            }
        }
    }

    public CinemachineTargetGroup getTargetGroup() {
        if (targetGroup == null) {
            targetGroup = gridContainer.GetComponentInChildren<CinemachineTargetGroup>();
        }

        return targetGroup;
    }

    public Tile getTileAtPosition(Vector2 pos) {
        if (tiles.TryGetValue(pos, out var tile)) {
            return tile;
        }
        return null;
    }
}
