using UnityEditor;
using UnityEngine;

namespace Floralin.Plants.Editor
{
    /// <summary>
    /// The inspector of the Floralin/VertexColor material: the species' palette colours under their names from the
    /// plant definition (leaf, sun, bark ...). Editing a colour recolours every model that uses the material, at every LOD;
    /// highlights and shadows follow, because they are blended from these colours in the shader. "Use palette colours"
    /// off shows the colours baked into the meshes instead. Light wrap softens the falloff past the light; translucency
    /// is how much sun comes through a face turned away from it (thin leaves and petals).
    /// </summary>
    public sealed class PaletteShaderGUI : ShaderGUI
    {
        /// <summary>The material tag that lists the slot names, comma separated, in slot order.</summary>
        public const string NamesTag = "FloralinPalette";

        public const int Slots = 24;

        public override void OnGUI(MaterialEditor editor, MaterialProperty[] properties)
        {
            var material = editor.target as Material;
            string names = material != null ? material.GetTag(NamesTag, false, "") : "";
            string[] labels = names.Length > 0 ? names.Split(',') : new string[0];

            editor.ShaderProperty(FindProperty("_UsePalette", properties), "Use palette colours");
            editor.ShaderProperty(FindProperty("_BaseColor", properties), "Tint");
            editor.ShaderProperty(FindProperty("_ReceiveShadows", properties), "Receive shadows");
            editor.ShaderProperty(FindProperty("_Wrap", properties), "Light wrap");
            editor.ShaderProperty(FindProperty("_Translucency", properties), "Translucency");
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Palette", EditorStyles.boldLabel);
            int count = labels.Length > 0 ? Mathf.Min(labels.Length, Slots) : Slots;
            for (int i = 0; i < count; i++)
            {
                MaterialProperty slot = FindProperty("_C" + i, properties);
                string label = i < labels.Length && labels[i].Length > 0 ? labels[i] : "Colour " + i;
                editor.ColorProperty(slot, label);
            }
            EditorGUILayout.Space();
            editor.RenderQueueField();
            editor.EnableInstancingField();
        }
    }
}
