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

public class Shower : MonoBehaviour
{
    public GameObject button;
    public bool isBeingUsed = false;
    public PlayerController playerUsingShower;

    public int playersInsideCounter = 0;
    public ParticleSystem showerParticle;
    public GameObject showerPosition;

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

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

    public void UseShower()
    {
        playerUsingShower.transform.position = showerPosition.transform.position;

        //GetComponent<SpriteRenderer>().sortingOrder+=5;
        playerUsingShower.GetComponent<SpriteRenderer>().sortingOrder = GetComponent<SpriteRenderer>().sortingOrder - 1;
        showerParticle.Play();
        isBeingUsed = true;
        InvokeRepeating("HealPlayer", 1f, 5f);

        //print("shower used");
    }

    public void HealPlayer()
    {
        playerUsingShower.Heal();
    }

    public void CheckShowerStatus()
    {
        if(isBeingUsed)
        {
            playerUsingShower.TakeDamage(1);
            FinishShower();
        }
    }

    public void FinishShower()
    {
        playerUsingShower.GetComponent<SpriteRenderer>().sortingOrder = GetComponent<SpriteRenderer>().sortingOrder + 1;
        showerParticle.Stop();
        CancelInvoke();

        isBeingUsed = false;

        playerUsingShower.canMove = true;
        playerUsingShower.showerInFrontOfMe = null;

        HideButton();

        //print("finished shower");

    }

    public void UsePhonOnShower(PlayerController playerUsingPhon)
    {
        playerUsingShower.TakeDamage(1);

        playerUsingPhon.isInFrontOfShower = false;
        playerUsingPhon.showerInFrontOfMe = null;

        FinishShower();
    }

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

            collision.gameObject.GetComponent<PlayerController>().isInFrontOfShower = true;
            collision.gameObject.GetComponent<PlayerController>().showerInFrontOfMe = GetComponent<Shower>();

        }
    }



    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            playersInsideCounter--;
            if (playersInsideCounter == 0)
                HideButton();

            collision.gameObject.GetComponent<PlayerController>().isInFrontOfShower = false;
            collision.gameObject.GetComponent<PlayerController>().showerInFrontOfMe = null;

        }
    }

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