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

public class SafePlace : MonoBehaviour {

    public Slider GetSlider { get { return slider; } }
    private Slider slider;
    private IEnumerator tmpCoroutine;
    private bool isTryingToHide;
    

    [SerializeField]
    private float sliderTime;

    [SerializeField]
    private float speed;
    
    private void Start()
    {
        slider = GameObject.Find("Canvas").GetComponentInChildren<Slider>();
        SafePlace[] otherSafePlaces = GameObject.FindObjectsOfType<SafePlace>();
        bool canHideSlider = true;
        foreach (SafePlace safe in otherSafePlaces)
        {
            if (safe.GetSlider == null)
            {
                canHideSlider = false;
            }
        }
        if (canHideSlider)
        {
            if(slider.gameObject.activeSelf == true)
            {
                slider.gameObject.SetActive(false);
            }
        }
    }
    private void OnCollisionStay(Collision collision)
    {
        if (collision.collider.name == "Player" && isTryingToHide == false)
        {
            if(isTryingToHide == false)
            {
                isTryingToHide = true;
            }
            if (tmpCoroutine == null)
            {
                tmpCoroutine = StartHiding(collision.gameObject);
                StartCoroutine(tmpCoroutine);
            }
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        isTryingToHide = false;

        if (collision.collider.name == "Player")
        {
            StopAllCoroutines();
            tmpCoroutine = null;
            slider.gameObject.SetActive(false);
        }
    }

    private IEnumerator StartHiding(GameObject _player)
    {
        if(_player.name == "Player")
        {
            slider.gameObject.SetActive(true);
            slider.value = 1f;
            float timeToDecrease = sliderTime;
            while (isTryingToHide)
            {
                yield return null;
                timeToDecrease -= Time.deltaTime * speed;
                slider.value = timeToDecrease / sliderTime;
                if (slider.value == 0f && _player.GetComponent<PlayerMovementController>().isHidden == false)
                {
                    HidePlayer(_player);
                }
            }
        }
        yield return null;
    }

    private void HidePlayer(GameObject player)
    {
        player.GetComponent<PlayerMovementController>().isHidden = true;
        player.GetComponentInChildren<SpriteRenderer>().enabled = false;
        slider.value = 1f;
        slider.gameObject.SetActive(false);
    }
}
