using UnityEngine;
using UnityEngine.InputSystem.XR;
using UnityEngine.XR.Interaction.Toolkit;

namespace EscapeRoomEngine.Portal.Runtime
{
    /// <summary>
    /// The clone of a <see cref="PortalDriver"/> is a copy of it that was stripped of most of its components. Its position is updated by the driver.
    /// </summary>
    public class PortalDriverClone : MonoBehaviour
    {
        /// <summary>
        /// The portal where this clone is mirroring the portal driver.
        /// </summary>
        [HideInInspector] public Portal portal;

        public static PortalDriverClone Create(PortalDriver portalDriver)
        {
            // copy the portal driver object
            var clone = Instantiate(portalDriver).gameObject;
            
            // destroy all unnecessary components
            Destroy(clone.GetComponent<PortalDriver>());
            foreach (var xrGrabInteractable in clone.GetComponentsInChildren<XRGrabInteractable>())
                Destroy(xrGrabInteractable);
            foreach (var rigidbody in clone.GetComponentsInChildren<Rigidbody>())
                Destroy(rigidbody);
            foreach (var trackedPoseDriver in clone.GetComponentsInChildren<TrackedPoseDriver>())
                Destroy(trackedPoseDriver);
            
            // add a clone component
            clone.AddComponent<PortalDriverClone>();
            
            // set up the clone
            var portalDriverClone = clone.GetComponent<PortalDriverClone>();
            portalDriverClone.gameObject.SetActive(false);
            return portalDriverClone;
        }

        public void UpdatePosition(Transform cloning)
        {
            var m = portal.portalTransform.localToWorldMatrix * Portal.HalfRotation *
                    portal.linkedPortal.portalTransform.worldToLocalMatrix * cloning.localToWorldMatrix;
            transform.SetPositionAndRotation(m.GetPosition(), m.rotation);
        }

        public override string ToString()
        {
            return gameObject.name;
        }
    }
}
