using System;
using System.Reflection;
using AGXUnity;
using UnityEngine;

public class FrictionControllerBridge : MonoBehaviour
{
  [SerializeField] private Constraint m_constraint = null;
  [SerializeField] private string m_variableName = "CurrentForce";

  public string VariableName { get => m_variableName; set => m_variableName = value; }
  public Constraint Constraint { get => m_constraint; set => m_constraint = value; }

  private static readonly Type s_variablesType = Type.GetType( "Unity.VisualScripting.Variables, Unity.VisualScripting.Core" );
  private static readonly MethodInfo s_objectMethod =
    s_variablesType?.GetMethod( "Object", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof( GameObject ) }, null );
  private static readonly MethodInfo s_setMethod =
    s_objectMethod?.ReturnType.GetMethod( "Set", new[] { typeof( string ), typeof( object ) } );

  private FrictionController m_frictionController = null;

  private void Awake()
  {
    if (m_constraint != null)
      m_frictionController = m_constraint.GetController<FrictionController>();
  }

  private void FixedUpdate()
  {
    if (s_setMethod == null)
      return;

    s_setMethod.Invoke( s_objectMethod.Invoke( null, new object[] { gameObject } ),
                        new object[] { m_variableName, m_frictionController?.GetCurrentForce() ?? 0.0f } );
  }
}
