using KitsuneCafe.SOAP;
using R3;
using UnityEngine;
using UnityEngine.InputSystem;

namespace KitsuneCafe.Input
{
  public class InputChangeHandler : MonoBehaviour
  {
    [SerializeField]
    private PlayerInput playerInput;

    [SerializeField]
    private ControlSchemeValue controlScheme;

    [SerializeField]
    private ActionMapValue actionMap;

    private void OnValidate()
    {
      if (playerInput == null)
      {
        playerInput = GetComponent<PlayerInput>();
      }
    }

    private void Start()
    {
      var d = Disposable.CreateBuilder();

      actionMap.AsObservable()
        .DistinctUntilChanged()
        .Subscribe(map =>
        {
          var name = map switch
          {
            ActionMap.Player => "Player",
            ActionMap.UI => "UI",
            _ => throw new System.NotImplementedException()
          };

          var inputActionMap = playerInput.actions.FindActionMap(name);
          playerInput.currentActionMap = inputActionMap;
        })
        .AddTo(ref d);

      controlScheme.Value = GetControlScheme(playerInput.currentControlScheme);

      Observable.FromEvent<PlayerInput>(
        e => playerInput.onControlsChanged += e,
        e => playerInput.onControlsChanged -= e
      )
        .Subscribe(value =>
        {
          controlScheme.Value = GetControlScheme(value.currentControlScheme);
        })
        .AddTo(ref d);

      d.RegisterTo(destroyCancellationToken);
    }

    private static ControlScheme GetControlScheme(string controlScheme)
    {
      return controlScheme switch
      {
        "Gamepad" => ControlScheme.Gamepad,
        "Keyboard&Mouse" => ControlScheme.KeyboardAndMouse,
        _ => ControlScheme.Other
      };
    }
  }
}
