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

public class RootDrawer : MonoBehaviour
{
	[SerializeField] private LineRenderer _lineRendererModel = null;
	[SerializeField] private Transform _linesRoot = null;
	[SerializeField] private int _maxRoot = 10;


	private List<LineRenderer> _lineRenderers = null;

	private LineRenderer _currentLineRenderer = null;
	private Rocket _currentRocket;

	private List<Vector3> _points = null;

	private bool _draw = false;

	private void Awake()
	{
		_lineRenderers = new List<LineRenderer>();
	}

	public void StartRoot(Rocket rocket)
	{
		_currentRocket = rocket;
		_currentRocket.ExplodeEvent += OnCurrentRocketExplode;
		_currentLineRenderer = Instantiate(_lineRendererModel, _linesRoot);

		_lineRenderers.Add(_currentLineRenderer);
		_points = new List<Vector3>();
		_draw = true;
	}

	private void Update()
	{
		if (_draw == false)
		{
			return;
		}

		Vector3 position = _currentRocket.transform.position;
		position.z = -0.1f;
		_points.Add(position);

		_currentLineRenderer.positionCount = _points.Count;
		_currentLineRenderer.SetPositions(_points.ToArray());
	}

	private void OnCurrentRocketExplode()
	{
		_draw = false;
		if (_lineRenderers.Count > _maxRoot)
		{
			StartCoroutine(DestroyRoot());
		}
	}

	private IEnumerator DestroyRoot()
	{
		LineRenderer renderer = _lineRenderers[0];
		_lineRenderers.RemoveAt(0);

		float time = 0.0f;
        while (renderer.widthMultiplier > 0.0f)
        {
			time += Time.deltaTime;
			renderer.widthMultiplier -= time;
			yield return null;
        }

		Destroy(renderer.gameObject);
	}
}
