using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;

public class EssenceNodeController : MonoBehaviour
{
    [SerializeField]
    private AudioSource chime;

    private Inventory playerInventory;

    public bool isTouched;
    private bool followPlayer = false;
    private Transform player;

    private float timer;
    private Material nodeMaterial;

    private Coroutine decayCo;

    private void Awake()
    {
        nodeMaterial = GetComponent<Renderer>().material;
        playerInventory = GameObject.Find("Inventory").GetComponent<Inventory>();
    }

    public void Touched()
    {
        if (!isTouched)
        {
            GetComponent<Renderer>().material.color = Color.cyan;
            chime.Play();
            isTouched = true;
            StopCoroutine(decayCo);
        }
    }

    public void FollowPlayer()
    {
        followPlayer = true;
        player = GameObject.FindGameObjectWithTag("MainCamera").transform;
        StartCoroutine(Collect());

    }

    public void SetPitch(float value)
    {
        chime.pitch = value;
    }

    public void SetTimer(float seconds)
    {
        timer = seconds;
        decayCo = StartCoroutine(Decay());
    }


    IEnumerator Collect()
    {
        yield return new WaitForSeconds(2f);
        //TODO: Update value in player inventory
        playerInventory.AddItem(GetComponent<ItemData>());
        Destroy(gameObject);
    }

    IEnumerator Decay()
    {
        yield return new WaitForSeconds(timer);
        Destroy(gameObject);
    }

    private void Update()
    {
        if (!isTouched)
        {
            //A way to either linearly reduce the alpha value of color or fade the color to gray (must react to changing timer values)
        }

        if (followPlayer)
        {
            transform.position = Vector3.Lerp(transform.position, new Vector3(player.position.x,player.position.y - 0.5f, player.position.z), Time.deltaTime);
        }
    }

}