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

public class BearIsAwake : MonoBehaviour
{
    public Transform Penguin;
    public Image bearTimer;

    private float timer = 0f;
    private bool wakingUp = false;
    public BearAwareness bearAwareness;
    
    public PositionReset[] thingstoReset;
    private void Start()
    {
        BearAwareness.HasWokenUp += IsAwake;
        
        thingstoReset = FindObjectsOfType<PositionReset>();
    }

    

    private void Update()
    {
        if (wakingUp)
        {
            timer += Time.deltaTime;
            bearTimer.fillAmount = timer / bearAwareness.timeToWakeUp;
        }
    }

    public void IsAwake(float time)
    {
        wakingUp = true;
       StartCoroutine(SleepIsOver(time));
    }

    IEnumerator SleepIsOver(float time)
    {
        yield return new WaitForSeconds(time);
        
        Vector3 direction = Penguin.position - transform.position;
        float distance = direction.magnitude;
        direction.Normalize(); // Wichtig: Raycast braucht eine normierte Richtung


        if (Physics.Raycast(transform.position, direction, out RaycastHit hit, distance))
        {
            Debug.Log("Getroffen: " + hit.collider.name);
            if (hit.collider.name == "StandUpCollider")
            {
                Debug.Log("Your Dead!");
               foreach (PositionReset things in thingstoReset)
               {
                   things.Reset();
               }
            }
            else
            {
                Debug.Log("What?");
            }

        }
        wakingUp = false;
        timer = 0f;
        bearTimer.fillAmount = 0;
        Debug.DrawLine(transform.position, Penguin.position, Color.red, 10f);
    }
}
