using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using NaughtyAttributes;
using UnityEngine;

namespace EscapeRoomEngine.Engine.Runtime
{
    [SuppressMessage("ReSharper", "InconsistentNaming")]
    public enum TileLocation
    {
        NW, N, NE,
        W,  C, E,
        SW, S, SE
    }

    [Serializable]
    public struct TilePrefab
    {
        public TileLocation location;
        public GameObject prefab;
    }

    /// <summary>
    /// A space tile contains all game objects necessary to create a space from 2m x 2m up to any size.
    /// </summary>
    public class SpaceTile : MonoBehaviour
    {
        public static HashSet<TileLocation> EveryTileLocation => new(new[]
        {
            TileLocation.NW, TileLocation.N, TileLocation.NE,
            TileLocation.W,  TileLocation.C, TileLocation.E,
            TileLocation.SW, TileLocation.S, TileLocation.SE
        });
        
        [BoxGroup("Style Prefabs")] [SerializeField]
        private List<TilePrefab> tilePrefabs;
        [BoxGroup("Style Prefabs")] [SerializeField]
        private Material material;
        
        public TileLocation showTile;

        private GameObject _tile;
        private TileLocation _showTile;

        private void Start()
        {
            SetTile();
        }

        private void Update()
        {
            if (_showTile != showTile)
            {
                SetTile();
            }
        }

        private void SetTile()
        {
            if (_tile)
            {
                Destroy(_tile);
            }

            _tile = Instantiate(tilePrefabs.Find(tilePrefab => tilePrefab.location == showTile).prefab, transform);
            _tile.isStatic = true;
            _tile.GetComponent<MeshRenderer>().material = material;
            
            var tileCollider = _tile.AddComponent<MeshCollider>();
            tileCollider.convex = true;
            tileCollider.sharedMesh = _tile.GetComponent<MeshFilter>().sharedMesh;

            _showTile = showTile;
        }
    }
}
