using System.Linq;
using UnityEngine;

namespace TFramework
{
    public class ObjectHighlight : MonoBehaviour
    {
        private Renderer[] _renderers;
        private Material _highlightMaskMaterial;
        [SerializeField]
        private Color _highlightColor;

        public Color HighlightColor
        {
            get => _highlightColor;
            set
            {
                _highlightColor = value;
                UpdateMaterialProperties();
            }
        }

        private void Awake()
        {
            _renderers = GetComponentsInChildren<Renderer>();
            _highlightMaskMaterial= Instantiate(Main.GetMagr<EffectManager>().m_hihghlightMaterial);
            _highlightMaskMaterial.name = "Highlight (Instance)";
            _highlightColor = Main.GetMagr<EffectManager>().m_defaultHighlightColor;
        }

        private void OnEnable()
        {
            foreach (var renderer in _renderers)
            {

                var materials = renderer.sharedMaterials.ToList();

                materials.Add(_highlightMaskMaterial);

                renderer.materials = materials.ToArray();
            }
            UpdateMaterialProperties();
        }

        private void OnDisable()
        {
            foreach (var renderer in _renderers)
            {

                var materials = renderer.sharedMaterials.ToList();

                materials.Remove(_highlightMaskMaterial);

                renderer.materials = materials.ToArray();
            }
        }

        private void OnDestroy()
        {
            foreach (var renderer in _renderers)
            {

                var materials = renderer.sharedMaterials.ToList();

                materials.Remove(_highlightMaskMaterial);

                renderer.materials = materials.ToArray();
            }
            Destroy(_highlightMaskMaterial);
        }

        void UpdateMaterialProperties()
        {
            _highlightMaskMaterial?.SetColor("_HighlightColor", _highlightColor);
        }
    }
}
