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

namespace Grid {
    public class LevelGrid : MonoBehaviour {
        [FormerlySerializedAs("GridDebugObjectPrefab")] [SerializeField]
        private Transform gridDebugObjectPrefab;

        [SerializeField] private int width = 20;
        [SerializeField] private int height = 20;
        [SerializeField] private float cellSize = 2f;

        private GridSystemHex<GridObject> gridSystemHex;

        public static LevelGrid Instance { get; private set; }

        private void Awake() {
            if (Instance is not null) {
                Debug.LogError($"There is more than one LevelGrid! {transform} - {Instance}");
                Destroy(gameObject);
                return;
            }

            Instance = this;
            gridSystemHex = new(width, height, cellSize, (g, gridPosition) => new(g, gridPosition));
        }

        private void Start() => Pathfinding.Instance.Setup(width, height, cellSize);

        public event EventHandler OnAnyUnitMovedGridPosition;

        public void AddUnitAtGridPosition(GridPosition gridPosition, Unit unit) => gridSystemHex.GetGridObject(gridPosition).UnitList.Add(unit);

        public List<Unit> GetUnitListAtGridPosition(GridPosition gridPosition) => gridSystemHex.GetGridObject(gridPosition).UnitList;
        public void RemoveUnitAtGridPosition(GridPosition gridPosition, Unit unit) => gridSystemHex.GetGridObject(gridPosition).UnitList.Remove(unit);

        public GridPosition GetGridPosition(Vector3 worldPosition) => gridSystemHex.GetGridPosition(worldPosition);
        public Vector3 GetWorldPosition(GridPosition gridPosition) => gridSystemHex.GetWorldPosition(gridPosition);
        public bool IsValidGridPosition(GridPosition gridPosition) => gridSystemHex.IsValidGridPosition(gridPosition);
        public int GetWidth() => gridSystemHex.Width;
        public int GetHeight() => gridSystemHex.Height;

        public void UnitMovedGridPosition(Unit unit, GridPosition fromGridPosition, GridPosition toGridPosition) {
            RemoveUnitAtGridPosition(fromGridPosition, unit);
            AddUnitAtGridPosition(toGridPosition, unit);
            OnAnyUnitMovedGridPosition?.Invoke(this, EventArgs.Empty);
        }

        public bool HasAnyUnitOnGridPosition(GridPosition gridPosition) => gridSystemHex.GetGridObject(gridPosition).UnitList.Count > 0;
        public Unit GetUnitAtGridPosition(GridPosition gridPosition) => gridSystemHex.GetGridObject(gridPosition).GetUnit();
        public IInteractable GetInteractableAtGridPosition(GridPosition gridPosition) => gridSystemHex.GetGridObject(gridPosition).Interactable;
        public void SetInteractableAtGridPosition(GridPosition gridPosition, IInteractable interactable) => gridSystemHex.GetGridObject(gridPosition).Interactable = interactable;
    }
}