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

public class GrabbableItem : MonoBehaviour
{
    public bool isUsable = true;
    public float coolDownTime = 10f;

    public int playersInsideCounter = 0;


    public GameObject button;

    public GameObject toBeSpawned;

    // Start is called before the first frame update
    void Start()
    {
        button.SetActive(false);
    }

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

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            button.SetActive(true);
            playersInsideCounter++;


        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            collision.gameObject.GetComponent<PlayerController>().isInFrontOfGrabbableItem = false;

            if(!collision.gameObject.GetComponent<PlayerController>().isBringingItem)
                collision.gameObject.GetComponent<PlayerController>().grabbableInFrontOfMe = null;

            playersInsideCounter--;
            if (playersInsideCounter == 0)
                HideButton();

        }
    }

    private void HideButton()
    {
        button.SetActive(false);
    }

    private void UpdateButtonStatus()
    {
        if (!isUsable)
            button.GetComponent<SpriteRenderer>().color = new Color(0, 0, 0, 0.5f);
        else
            button.GetComponent<SpriteRenderer>().color = new Color(1, 1, 1, 1);
    }


    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {


            collision.gameObject.GetComponent<PlayerController>().isInFrontOfGrabbableItem = true;
            collision.gameObject.GetComponent<PlayerController>().grabbableInFrontOfMe = gameObject;
            UpdateButtonStatus();

            /*
            if (collision.gameObject.GetComponent<PlayerController>().IsPressing())
            {

                collision.gameObject.GetComponent<PlayerController>().BringSomething(gameObject);
                //isUsable = false;

                //Invoke("StopCoolDown", coolDownTime);
            }*/


        }
    }

    public void StopCoolDown()
    {
        isUsable = true;
        UpdateButtonStatus();
    }

}
