using System.Collections.Generic;
using UnityEngine;

namespace Cryville.EEW.Unity.Map {
	class MultiLineRenderer : MonoBehaviour {
		[SerializeField]
		LineRenderer m_lineRendererPrefab;
		public LineRenderer LineRenderer {
			get => m_lineRendererPrefab;
			set {
				if (m_lineRendererPrefab == value) return;
				m_lineRendererPrefab = value;
			}
		}

		[SerializeField]
		float m_width = 1;
		public float Width {
			get => m_width;
			set {
				if (m_width == value) return;
				m_width = value;
				for (int i = 0; i < _segmentIndex; i++) {
					_segments[i].Width = value;
				}
			}
		}

		[SerializeField]
		float m_tilingScale = 1;
		public float TilingScale {
			get => m_tilingScale;
			set {
				if (m_tilingScale == value) return;
				m_tilingScale = value;
				for (int i = 0; i < _segmentIndex; i++) {
					_segments[i].TilingScale = value;
				}
			}
		}

		int _segmentIndex;
		readonly List<LineRenderer> _segments = new();
		public void AddSegment(Vector2[] positions) => AddSegment(positions, 0, positions.Length);
		public void AddSegment(Vector2[] positions, int index, int length) {
			LineRenderer segment;
			if (_segmentIndex >= _segments.Count) {
				_segments.Add(segment = Instantiate(m_lineRendererPrefab, transform, false).GetComponent<LineRenderer>());
			}
			else {
				segment = _segments[_segmentIndex];
				segment.gameObject.SetActive(true);
			}
			_segmentIndex++;
			segment.SetPositions(positions, index, length);
			segment.Width = m_width;
			segment.TilingScale = m_tilingScale;
		}
		public void Clear() {
			for (int i = 0; i < _segmentIndex; i++) {
				_segments[i].gameObject.SetActive(false);
			}
			_segmentIndex = 0;
		}

		public void SetMaterial(Material material) {
			foreach (var r in _segments) {
				r.Material = material;
			}
		}
	}
}
