﻿using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using VRC.SDKBase;

[ExecuteAlways]
public class MirrorX : MonoBehaviour, IEditorOnly
{
    public GameObject ObjectToMirror; // The right-hand object
    public GameObject ObjectToMove;   // The left-hand object to mirror to

    [SerializeField] private Transform avatarTransform; // Reference to the avatar's root transform

    public Transform AvatarTransform
    {
        get => avatarTransform;
        private set => avatarTransform = value; // Only allow setting through the script
    }

    void Update()
    {

        MirrorObjects();

    }

    private void OnTransformParentChanged()
    {
        // Set AvatarTransform to the new parent
        AvatarTransform = transform.parent;

        // Optional: Log the new AvatarTransform for debugging
        if (AvatarTransform != null)
        {
            Debug.Log("Avatar Transform updated to: " + AvatarTransform.name);
        }
        else
        {
            Debug.LogWarning("Avatar Transform is null.");
        }
    }

    private void OnValidate()
    {
        // Ensure AvatarTransform is set correctly when in edit mode
        if (transform.parent != null && AvatarTransform == null)
        {
            AvatarTransform = transform.parent; // Assign the parent transform only if AvatarTransform is not already set
        }
    }

    private void MirrorObjects()
    {
        // Check if objects are assigned
        if (ObjectToMirror == null || ObjectToMove == null || AvatarTransform == null)
            return;

        // Mirror position relative to the avatar's position
        Vector3 mirroredPosition = AvatarTransform.position + new Vector3(
            -(ObjectToMirror.transform.position.x - AvatarTransform.position.x),
            ObjectToMirror.transform.position.y - AvatarTransform.position.y,
            ObjectToMirror.transform.position.z - AvatarTransform.position.z
        );

        ObjectToMove.transform.position = mirroredPosition;

        // Mirror rotation relative to the avatar's rotation
        Quaternion mirroredRotation = Quaternion.Euler(
            ObjectToMirror.transform.rotation.eulerAngles.x,
            -ObjectToMirror.transform.rotation.eulerAngles.y,
            -ObjectToMirror.transform.rotation.eulerAngles.z
        );

        ObjectToMove.transform.rotation = mirroredRotation;
    }
}