using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Serialization;

[RequireComponent(typeof(Collider))]
public class Killbox : MonoBehaviour
{
    [SerializeField] private bool _instakill = false;
    
    private Collider _box;
    private PlayerDeath _player;

    [SerializeField] private UnityEvent _playerEnter;
    [SerializeField] private UnityEvent _playerExit;
    
    private void Awake()
    {
        _box = GetComponent<Collider>();
        _box.isTrigger = true;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out PlayerDeath pd) && !_player)
        {
            _player = pd;
            
            if (_instakill)
            {
                KillPlayer();
                return;
            }
            
            _playerEnter.Invoke();
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.TryGetComponent(out PlayerDeath pd) && _player)
        {
            if (pd == _player)
            {
                _player = null;
                _playerExit.Invoke();
            }
            else
            {
                Debug.LogError($":thonk:", this);
            }
        }
    }

    public void KillPlayer()
    {
        if (!enabled) return;
        
        // can't kill out of bounds player
        if (!_player) return;
        
        _player.Respawn();
    }
}
