using UnityEngine;

namespace BR.BattleRoyale
{
#if UNITY_EDITOR
    [ExecuteAlways]
#endif
    public class SetTerrainData : MonoBehaviour
    {
#if UNITY_EDITOR
        [Header("Drop Terrain Data Here")]
        [SerializeField] TerrainData m_newData;

        Terrain m_terrain => GetComponent<Terrain>();
        TerrainCollider m_terrainCollider => GetComponent<TerrainCollider>();

        void OnValidate()
        {
            if (!m_terrain || !m_terrainCollider)
            {
                UnityEditor.EditorUtility.DisplayDialog("Invalid Component", "SetTerrainData component can only be placed on Terrain objects.", "OK");

                DestroyImmediate(this);
                return;
            }

            if (m_newData != null)
            {
                m_terrain.terrainData = m_newData;
                m_terrainCollider.terrainData = m_newData;

                m_newData = null;
            }
        }
        void Awake()
        {
            if (!m_terrain || !m_terrainCollider)
            {
                UnityEditor.EditorUtility.DisplayDialog("Terrain Required",
                    "The SetTerrainData script cannot be added to a non-terrain object.",
                    "Okay");

                DestroyImmediate(this);
                return;
            }
        }

        // Safe
        [UnityEditor.MenuItem("CONTEXT/Terrain/Set Basic")]
        static void SetBasicLayers(UnityEditor.MenuCommand command)
        {
            SetBasicLayers((Terrain)command.context);
        }
        public static void SetBasicLayers(Terrain _terrain)
        {
            if (!_terrain)
                return;

            TerrainLayer[] _layers = Resources.LoadAll<TerrainLayer>("Terrain Layers");

            _terrain.terrainData.terrainLayers = new TerrainLayer[] {
                _layers[0],
                _layers[1],
                _layers[3],
                _layers[9]
            };
        }

        [UnityEditor.MenuItem("CONTEXT/Terrain/Set Realistic")]
        static void SetRealisticLayers(UnityEditor.MenuCommand command)
        {
            SetRealisticLayers((Terrain)command.context);
        }
        public static void SetRealisticLayers(Terrain _terrain)
        {
            if (!_terrain)
                return;
            
            TerrainLayer[] _layers = Resources.LoadAll<TerrainLayer>("Terrain Layers");

            _terrain.terrainData.terrainLayers = new TerrainLayer[] {
                _layers[10],
                _layers[11],
                _layers[12],
                _layers[13],
                _layers[14]
            };
        }
#endif
    }
}