using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace TFramework
{
    [DisallowMultipleComponent]
    [ExecuteInEditMode]
    public class PrefabLMData : MonoBehaviour
    {
        [System.Serializable]
        internal struct RendererInfo
        {
            public Renderer renderer;
            public int lightmapIndex;
            public Vector4 lightmapOffsetScale;
        }

        [SerializeField]
        internal RendererInfo[] m_RendererInfo;
        [SerializeField]
        internal Texture2D[] m_LightmapsColor;
        [SerializeField]
        internal Texture2D[] _lightmapsDir;

        void Awake()
        {
            if (m_RendererInfo == null || m_RendererInfo.Length == 0)
                return;

            var lightmaps = LightmapSettings.lightmaps;
            var combinedLightmaps = new LightmapData[lightmaps.Length + m_LightmapsColor.Length];

            lightmaps.CopyTo(combinedLightmaps, 0);
            for (int i = 0; i < m_LightmapsColor.Length; i++)
            {
                combinedLightmaps[i + lightmaps.Length] = new LightmapData();
                combinedLightmaps[i + lightmaps.Length].lightmapColor = m_LightmapsColor[i];
                combinedLightmaps[i + lightmaps.Length].lightmapDir = _lightmapsDir[i];

            }

            ApplyRendererInfo(m_RendererInfo, lightmaps.Length);
            LightmapSettings.lightmaps = combinedLightmaps;
        }


        static void ApplyRendererInfo(RendererInfo[] infos, int lightmapOffsetIndex)
        {
            for (int i = 0; i < infos.Length; i++)
            {
                var info = infos[i];
                if (info.renderer != null)
                {
                    info.renderer.lightmapIndex = info.lightmapIndex + lightmapOffsetIndex;
                    info.renderer.lightmapScaleOffset = info.lightmapOffsetScale;
                }
            }
        }
    }
}
