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

[RequireComponent(typeof(LineRenderer))]
public class HookRenderer : MonoBehaviour
{
	[SerializeField]
	private LineRenderer lineRenderer;

	private Vector3 hookPosition;

    void Start()
    {
		Initialize();
    }

	private void Initialize()
	{
		if(lineRenderer == null)
		{
			lineRenderer = GetComponent<LineRenderer>();
		}
	}

	private void OnEnable()
	{
		EventManager.StartListening(EventNames.UPDATE_HOOK_POSITION, NewHook);
		EventManager.StartListening(EventNames.RELEASE_HOOK, ReleaseHook);
	}

	private void OnDisable()
	{
		EventManager.StopListening(EventNames.UPDATE_HOOK_POSITION, NewHook);
		EventManager.StopListening(EventNames.RELEASE_HOOK, ReleaseHook);
	}

	private void NewHook(Vector3 newHookPosition)
	{
		hookPosition = newHookPosition;
		EnableRope();
	}

	private void EnableRope()
	{
		UpdateLineRenderer();
		lineRenderer.enabled = true;
	}

	private void ReleaseHook()
	{
		DisableRope();
	}

	private void DisableRope()
	{
		lineRenderer.enabled = false;
	}

	private void LateUpdate()
	{
		UpdateLineRenderer();
	}

	private void UpdateLineRenderer()
	{
		lineRenderer.SetPositions(
			new Vector3[] {
				transform.position,
				hookPosition
			});
	}
}
