using System.Collections.Generic;
using UnityEngine;

namespace Cryville.Crtr.Skin.Components {
	public class TrackLine : SectionalGameObject {
		readonly List<Vector3> vertices = new List<Vector3>();

		LineRenderer lineRenderer;

		public TrackLine() {
			SubmitProperty("width", new PropOp.Float(v => Width = v));
		}

		private float m_width;
		public float Width {
			get { return m_width; }
			set {
				m_width = value;
				if (lineRenderer != null) {
					lineRenderer.startWidth = value;
					lineRenderer.endWidth = value;
				}
			}
		}

		public override void Init() {
			lineRenderer = gameObject.AddComponent<LineRenderer>();
			lineRenderer.materials = materials = new Material[] { MeshWrapper.NewMaterial() };
			Width = Width;
			base.Init();
		}

		protected override void UpdateColor() {
			base.UpdateColor();
			if (lineRenderer != null) {
				lineRenderer.startColor = Color;
				lineRenderer.endColor = Color;
			}
		}

		protected override void AppendPointInternal(Vector3 p, Quaternion r) {
			vertices.Add(p);
		}

		public override void Seal() {
#if UNITY_5_6_OR_NEWER
			lineRenderer.positionCount = vertices.Count;
#else
			lineRenderer.SetVertexCount(vertices.Count);
#endif
			for (int i = 0; i < vertices.Count; i++) lineRenderer.SetPosition(i, vertices[i]);
		}

		public override void Reset() {
			base.Reset();
			vertices.Clear();
		}
	}
}
