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

public delegate void OnLinkUpdate(int linkLeft);

public class ThreadController : MonoBehaviour
{
    public event OnLinkUpdate onLinkUpdateHandler;
    public List<GameObject> anchorPoints = new List<GameObject>();
    public LineRenderer lineRenderer;
    public int linkUsed;
    
    private List<Vector3> linePos = new List<Vector3>();

    // Start is called before the first frame update
    void Start()
    {
        PatchBehaviour.onPatchTriggered += PatchTriggerHandler;
        if (lineRenderer == null) lineRenderer = gameObject.GetComponent<LineRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
    }

    void RenderThreadline()
    {
        linePos.Clear();
        linePos = new List<Vector3>(new Vector3[anchorPoints.Count]);
        for (int i = 0; i < linePos.Count; i++)
        {
            linePos[i] = anchorPoints[i].transform.position;
        }

        lineRenderer.positionCount = linePos.Count;
        lineRenderer.SetPositions(linePos.ToArray());
    }

    void PatchTriggerHandler(GameObject obj)
    {
        Debug.Log("Player has entered a patch");
        if (anchorPoints.Count == 0)
        {
            anchorPoints.Add(obj);
        }
        else if (anchorPoints[anchorPoints.Count-1] != obj){
            if (anchorPoints.Count == 1 ||
                obj != anchorPoints[anchorPoints.Count - 2])
            {
                linkUsed++;
                anchorPoints.Add(obj);
            }
            else
            {
                linkUsed--;
                anchorPoints.RemoveAt(anchorPoints.Count - 1);
            }
            
            if (onLinkUpdateHandler != null)
            {
                onLinkUpdateHandler(linkUsed);
            }
        }
        
        RenderThreadline();
    }
}

