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 GridSystem<GridObject> gridSystem;

        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;
            gridSystem = 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) => gridSystem.GetGridObject(gridPosition).UnitList.Add(unit);

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

        public GridPosition GetGridPosition(Vector3 worldPosition) => gridSystem.GetGridPosition(worldPosition);
        public Vector3 GetWorldPosition(GridPosition gridPosition) => gridSystem.GetWorldPosition(gridPosition);
        public bool IsValidGridPosition(GridPosition gridPosition) => gridSystem.IsValidGridPosition(gridPosition);
        public int GetWidth() => gridSystem.Width;
        public int GetHeight() => gridSystem.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) => gridSystem.GetGridObject(gridPosition).UnitList.Count > 0;
        public Unit GetUnitAtGridPosition(GridPosition gridPosition) => gridSystem.GetGridObject(gridPosition).GetUnit();
        public IInteractable GetInteractableAtGridPosition(GridPosition gridPosition) => gridSystem.GetGridObject(gridPosition).Interactable;
        public void SetInteractableAtGridPosition(GridPosition gridPosition, IInteractable interactable) => gridSystem.GetGridObject(gridPosition).Interactable = interactable;
    }
}