using System;
using UnityEngine;

namespace Hazards
{
    /// <summary>
    /// 
    /// This script currently allows only for one fire Extinguisher per scene / level.
    /// If adding more to the level, we need to change the instantiation in OnEnable and use a FireExtinguisherManager.
    ///
    /// Whenever a fire is instantiated, it is a child object of the ignitable.
    /// 
    /// </summary>
    public class Fire : MonoBehaviour
    {
        public float fireMaxValue = 2f;
        public float currentFire;
        
        public bool extinguishing = false;

        public FireExtinguisher fireExtinguisher;

        private void OnEnable()
        {
            currentFire = fireMaxValue;
            fireExtinguisher = FindAnyObjectByType<FireExtinguisher>();
        }

        private void Update()
        {
            if (extinguishing)
            {
                currentFire -= 1f * Time.deltaTime;
            }

            if (currentFire <= 0.01f)
            {
                // Inform the ignitable about the extinction 
                var ignitable = transform.parent.GetComponent<Ignitable>();
                ignitable.isIgnited.Value = false;
                Destroy(gameObject);
            }
        }

        private void OnTriggerStay2D(Collider2D other)
        {
            if (fireExtinguisher.onMouseDown)
            {
                if (other.CompareTag("Extinguisher"))
                {
                    extinguishing = true;
                }   
            }
            else
            {
                extinguishing = false;
            }
        }

        private void OnTriggerExit2D(Collider2D other)
        {
            if (other.CompareTag("Extinguisher"))
            {
                extinguishing = false;   
            }
        }
    }
}
