using AGXUnity;
using AGXUnity.IO.OpenPLX;
using UnityEngine;
using UnityEngine.InputSystem;

/// <summary>
/// This script is a ported version of the controller provided in the t06-signal-interface OpenPLX tutorial, using the InputActionMapper
/// </summary>
public class BoxTruckSignals : MonoBehaviour
{
  // Expose scaling factors used when mapping InputActions to OpenPLX signals
  public float Amplitude = 3.0f;
  public InputActionAsset ActionMapAsset;

  SignalInterface m_boxtruckInterface;
  InputActionMapper m_actionMapper;

  void Start()
  {
    // Setup signal mapper
    var signals = GetComponent<OpenPLXSignals>().GetInitialized();
    m_actionMapper = new InputActionMapper( ActionMapAsset, "Boxtruck" );

    // Create maps from InputActions to OpenPLX inputs
    m_boxtruckInterface = signals.Interfaces[ 0 ];
    m_actionMapper.CreateMap( m_boxtruckInterface.FindInput( "right_wheel_angular_vel_input" ), "Drive", -Amplitude );
    m_actionMapper.CreateMap( m_boxtruckInterface.FindInput( "left_wheel_angular_vel_input" ), "Drive", Amplitude );
  }

  private void OnGUI()
  {
    // Display a GUI label for each output signal present in the interface and their last values
    foreach ( var output in m_boxtruckInterface.Outputs ) {
      if ( !output.HasSentSignal )
        continue;
      var outputType = OpenPLXSignals.GetOpenPLXTypeEnum(output.ValueTypeCode);
      var strippedName = output.Name[(output.Name.LastIndexOf('.') + 1)..];
      if ( outputType == OpenPLXSignals.ValueType.Real )
        GUILayout.Label( $"{strippedName}: {output.GetValue<float>()}" );
      else if ( outputType == OpenPLXSignals.ValueType.Vec3 )
        GUILayout.Label( $"{strippedName}: {output.GetValue<Vector3>()}" );
    }
  }
}
