using Sirenix.OdinInspector;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UIElements;

public class UsersInputListener : MonoBehaviour
{

    [Header("Design in Editor")]
    [SerializeField]
    JoystickVRPN joystickVRPN;
    [SerializeField]
    GameObject prefabToInstantiate;
    [SerializeField]
    Transform parentContainer;
    [SerializeField]
    UnityEvent userGeneratedEvent;
    [Space]
    [Header("Runtime Debug")]
    [SerializeField]
    List<UserAgentManager> allManagers;


    //this can send events for all the buttons that is has registered, for the whole room
    //it will send them in a format int,int,bool, where int = 

    private void OnEnable()
    {
        allManagers = new List<UserAgentManager>();
        joystickVRPN.OnButtonChange.AddListener(RespondToButtonEvents);
    }
    private void OnDisable()
    {
        joystickVRPN.OnButtonChange.RemoveListener(RespondToButtonEvents);
    }

    void RespondToButtonEvents(int SeatIndex, int ButtonIndex, bool IsPressed)
    {
        Debug.Log("The Users Input listener heard a button press at seat " + SeatIndex);
        //right now, I only want to spawn players based on the first ever button click
        QueryExistingManagers(SeatIndex);
    }

    [Button("QueryExistingManagers")]
    private void QueryExistingManagers(int SeatIndex)
    {
        foreach (var item in allManagers)
        {
            if (item.seatIndex == SeatIndex)
            {
                return;
            }
        }

        //if you have reached here, this seated player doesn't exist yet
        SpawnUserAgentPrefab(SeatIndex);
    }

    public void SpawnUserAgentPrefab(int SeatIndex)
    {
        GameObject instantiatedPrefab = Instantiate(prefabToInstantiate, parentContainer);
        UserAgentManager newAgent = instantiatedPrefab.GetComponentInChildren<UserAgentManager>();
        allManagers.Add(newAgent);
        //assign the proper seat to the spawned prefab
        newAgent.AssignSeat(SeatIndex);
        //initialize it from there on
        userGeneratedEvent?.Invoke();
    }

    public void RemoveAgent(UserAgentManager agent)
    {
        allManagers.Remove(agent);
    }


}
