using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Collider2D))]
public class HazardHitbox : MonoBehaviour
{
    [SerializeField] private LayerMask _targetLayer;
    [SerializeField] private LayerMask _blockLayer;
    public int Damage = 0;
    private Collider2D _collider;
    private void Awake()
    {
        _collider = GetComponent<Collider2D>();
        _collider.isTrigger = true;
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if((_blockLayer.value & (1 << other.gameObject.layer)) > 0)
        {
            Destroy(gameObject);
        }

        if ((_targetLayer.value & (1 << other.gameObject.layer)) > 0)
        {
            TryDamage(other);
            _collider.enabled = false;    
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if ((_targetLayer.value & (1 << other.gameObject.layer)) > 0)
        {
            Destroy(gameObject);
        }
    }

    private void TryDamage(Collider2D other)
    {
        if (!other.TryGetComponent<IDamageable>(out var target))
            target = other.GetComponentInParent<IDamageable>();
        if (target == null) return;

        target.TakeDamage(Damage);
    }
}
