﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

public class LookAtPlayerYawOnly : UdonSharpBehaviour
{
    // optimization: run every 3 frames
    private int RUN_FREQ = 3;
    private int frameCounter = 0;

    public bool followPlayerGaze = false;

    // Set by the script that owns this transform's pose (e.g. a carried readout) so only one writer touches it.
    public bool externallyDriven = false;

    // Hover straight above the parent in world space instead of at a fixed local position, so a grabbed and rotated
    // parent (a chip pile) doesn't swing the readout around with it.
    public bool useWorldYOffset = false;
    public float worldYOffset = 0f;

    private VRCPlayerApi player;

    private void OnEnable()
    {
        player = Networking.LocalPlayer;
    }

    void Start()
    {
        player = Networking.LocalPlayer;
    }

    // PostLateUpdate runs after every Update/LateUpdate and after pickups move, so a parent that is carried
    // by a pickup cannot drag this transform away from the pose written here.
    public override void PostLateUpdate()
    {
        if (externallyDriven) return;

        if (useWorldYOffset && transform.parent != null)
            transform.position = transform.parent.position + Vector3.up * worldYOffset;

        // A readout riding on a grabbed pile inherits the pile's rotation on every frame this skips, so it must
        // run every frame; only the free-standing readouts can afford the throttle.
        if (!useWorldYOffset)
        {
            frameCounter++;

            if (frameCounter < RUN_FREQ)
            {
                return;
            }

            frameCounter = 0;
        }

        if (player == null) return;

        VRCPlayerApi.TrackingData headData =
            player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head);

        if (followPlayerGaze)
        {
            // Follow player's head/view rotation on all axes.
            // Negate forward because this object's visual forward is -Z.
            Vector3 playerForward = headData.rotation * Vector3.forward;
            Vector3 playerUp = headData.rotation * Vector3.up;

            transform.rotation = Quaternion.LookRotation(playerForward, playerUp);
            return;
        }

        // Look at player, yaw only.
        Vector3 playerPos = headData.position;

        Vector3 direction = playerPos - transform.position;
        direction.y = 0f;

        if (direction.sqrMagnitude < 0.001f) return;

        Quaternion rotation = Quaternion.LookRotation(-direction, Vector3.up);

        transform.rotation = rotation;
    }
}
