using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;

public class NetworkPlayerTransform : NetworkBehaviour
{
    public float syncErrorAmount = 1f;
    public bool syncPosition = false;
    public bool syncLocalRotation = false;
    private NetworkVariable<Vector3> position = new NetworkVariable<Vector3>(default, default, NetworkVariableWritePermission.Owner);
    private NetworkVariable<Quaternion> localRotation = new NetworkVariable<Quaternion>(default, default, NetworkVariableWritePermission.Owner);

    public override void OnNetworkSpawn()
    {
        if (IsClient) {
            position.OnValueChanged += OnPositionChangedDelegate;
            localRotation.OnValueChanged += OnLocalRotationChangedDelegate;
        }

        base.OnNetworkSpawn();
    }

    private void Update()
    {
        if (IsServer) {
            if (syncPosition) {
                position.Value = transform.position;
            }
            if (syncLocalRotation) {
                localRotation.Value = transform.localRotation;
            }
        }
    }

    public void OnPositionChangedDelegate(Vector3 previousValue, Vector3 newValue)
    {
        if (syncPosition == false) {
            return;
        }
        if (IsClient == false) {
            return;
        }
        if (Vector3.Distance(newValue, transform.position) > syncErrorAmount) {
            transform.position = newValue;
        }
    }

    public void OnLocalRotationChangedDelegate(Quaternion previousValue, Quaternion newValue)
    {
        if (syncLocalRotation == false) {
            return;
        }
        if (IsClient == false) {
            return;
        }
        if (Quaternion.Angle(newValue, transform.localRotation) > syncErrorAmount) {
            transform.localRotation = newValue;
        }
    }
}
