using UnityEngine;

namespace Jovian.Utilities {

    public class CustomRenderQueueRenderer : MonoBehaviour {
        [SerializeField, Tooltip("Override RenderQueue for shader, 2000 = Opaque, 3000 = Transparent, -1 = Shader Default")]
        private int renderQueue = -1;
        [SerializeField]
        private MeshRenderer meshRenderer;
        [SerializeField, Tooltip("If true, only this renderer is affected because a new material is created.")]
        private bool createMaterialInstance;

        private void Awake() {
            var material = createMaterialInstance ? meshRenderer.material : meshRenderer.sharedMaterial;
            material.renderQueue = renderQueue;
        }

#if UNITY_EDITOR
        private void Reset() {
            var serializedObject = new UnityEditor.SerializedObject(this);
            var meshRendererProperty = serializedObject.FindProperty("meshRenderer");
            var meshRenderer = gameObject.GetComponent<MeshRenderer>();
            if(meshRenderer != null) {
                meshRendererProperty.objectReferenceValue = meshRenderer;
                serializedObject.ApplyModifiedProperties();
                CopyRenderQueueFromMaterial(); // applies serializedObject modified properties
            }
        }

        [ContextMenu("Copy RenderQueue from Material")]
        private void CopyRenderQueueFromMaterial() {
            if(meshRenderer == null) {
                Debug.LogError(@"MeshRenderer is null, cannot copy RenderQueue", this);
                return;
            }
            var serializedObject = new UnityEditor.SerializedObject(this);
            var renderQueueProperty = serializedObject.FindProperty("renderQueue");
            renderQueueProperty.intValue = meshRenderer.sharedMaterial.renderQueue;
            serializedObject.ApplyModifiedProperties();
        }
#endif
    }
}