using System.Collections.Generic;
using UnityEngine;

namespace GGJ.LightRenderer
{
    public class Line : MonoBehaviour, ILightRenderer
    {
        private List<LineRenderer> renderers = new List<LineRenderer>();
        private List<LineRenderer> inuse = new List<LineRenderer>();
        public Material material;
        private float dist;
        private LineRenderer Next()
        {
            if (renderers.Count == 0)
            {
                var go = new GameObject("renderer_" + ((renderers.Count + inuse.Count) + 1));
                go.transform.parent = this.transform;
                var lr = go.AddComponent<LineRenderer>();
                inuse.Add(lr);
                lr.material = material;
                return lr;
            }
            var r = renderers[0];
            renderers.RemoveAt(0);
            inuse.Add(r);
            return r;
        }

        public void Draw(LightSegment segment)
        {
            var lineRenderer = Next();
            lineRenderer.startColor = segment.color;
            lineRenderer.endColor = segment.color;
            lineRenderer.startWidth = segment.startsWith;
            lineRenderer.endWidth = segment.endsWidth;
            var poses = new List<Vector3> {segment.start, segment.end};
            lineRenderer.numPositions = poses.Count;
            lineRenderer.SetPositions(poses.ToArray());
        }

        public void Clear()
        {
            foreach (var lineRenderer in inuse)
            {
                lineRenderer.numPositions = 0;
                renderers.Add(lineRenderer);
            }
            inuse.Clear();
        }

        public void SetDistanceTravelled(float dist)
        {
            this.dist = dist;
        }
    }
}