using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Saltosion.OneWeapon.Effects;

namespace Saltosion.OneWeapon.Utils {

    [ExecuteInEditMode]
    public class LightUpdater : MonoBehaviour {
        public Material Material;
        public Material ParticleMat;

        [HideInInspector]
        private List<CustomLight> Lights = new List<CustomLight>();

        void Update() {
            Vector4[] PosList = new Vector4[500];
            float[] IntensityList = new float[500];
            float[] SizeList = new float[500];
            Color[] ColorList = new Color[500];

            List<int> ToRemove = new List<int>();
            for (int i = 0; i < Lights.Count; i++) {
                if (Lights[i] == null) {
                    ToRemove.Add(i);
                    continue;
                }
                PosList[i] = Lights[i].transform.position;
                IntensityList[i] = Lights[i].LightIntensity;
                SizeList[i] = Lights[i].LightSize;
                ColorList[i] = Lights[i].LightTint;
            }

            foreach (int i in ToRemove) {
                Lights.RemoveAt(i);
            }

            Material.SetInt("_LightCount", Lights.Count);
            Material.SetVectorArray("_LightLocations", PosList);
            Material.SetFloatArray("_LightIntensities", IntensityList);
            Material.SetFloatArray("_LightSizes", SizeList);
            Material.SetColorArray("_LightColors", ColorList);

            ParticleMat.SetInt("_LightCount", Lights.Count);
            ParticleMat.SetVectorArray("_LightLocations", PosList);
            ParticleMat.SetFloatArray("_LightIntensities", IntensityList);
            ParticleMat.SetFloatArray("_LightSizes", SizeList);
            ParticleMat.SetColorArray("_LightColors", ColorList);
        }

        public void RegisterLight(CustomLight Light) {
            if (Light != null) {
                Lights.Add(Light);
            }
        }

        public void UnregisterLight(CustomLight Light) {
            int idx = Lights.IndexOf(Light);
            if (idx > 0) {
                Lights.Remove(Light);
            }
        }
    }
}
