using EscapeRoomEngine.Engine.Runtime.Utilities;
using UnityEngine;

namespace Station46.Scripts
{
    /// <summary>
    /// An object that will be placed in its original position if it falls off the platform.
    /// </summary>
    [RequireComponent(typeof(Collider), typeof(Rigidbody))]
    public class Respawning : MonoBehaviour
    {
        private Vector3 _spawnPosition;
        private Quaternion _spawnRotation;
        private Rigidbody _rigidbody;

        private void Awake()
        {
            _rigidbody = GetComponent<Rigidbody>();
            
            if (GetComponent<Collider>().isTrigger)
            {
                throw new WrongTypeException($"{this} must have a rigidbody collider.");
            }
        }

        private void Start()
        {
            var t = transform;
            _spawnPosition = t.position;
            _spawnRotation = t.rotation;
        }

        private void OnTriggerEnter(Collider other)
        {
            var respawnTrigger = other.GetComponent<RespawnTrigger>();
            if (respawnTrigger)
            {
                transform.SetPositionAndRotation(_spawnPosition, _spawnRotation);
                _rigidbody.velocity = Vector3.zero;
                _rigidbody.angularVelocity = Vector3.zero;
            }
        }
    }
}