using Assets.Scripts.NohaMorte;
using System;
using TMPro;
using UnityEngine;

//this script creates a user agnet prefba when the user presses any button on their seat if they dont have one already
//and destroys the agent if the user is idle for too long
//the agent needs to have the spawn location provided by them. This will be calculated in a different script.

public class UserAgentManager : MonoBehaviour
{
    [Header("Design in Editor")]
    //[SerializeField]
    //VRPN_Button[] buttons;
    [Space]
    [Header("Runtime Debug")]
    [SerializeField]
    JoystickVRPN joystickVRPN;

    public int seatIndex;
    [SerializeField]
    bool debugMode;
    [SerializeField]
    TextMeshProUGUI text;

    //[SerializeField]
    //string baseTrackerName;

    public ButtonPad buttonPad;

    public void AssignSeat(int SeatIndex)
    {
        seatIndex = SeatIndex;
        if (debugMode)
            text.text = seatIndex.ToString();

        joystickVRPN.OnButtonChange.AddListener(SubscribeToUserInput);
        Debug.Log("The UserAgentManager at seat " + SeatIndex + " was initialized.");

        //NO LONGER APPLICABLE
        ////find your DomeSeat from a source file based on the index
        //foreach (var item in buttons)
        //{
        //    //the button asks the host for its state based on tracker name. The button expects this from me. Since I am initializing it during runtime, I need to provide it.
        //    //the tracker name is important since its convereted to the address which the nativebridge will poll for data
        //    //therefore this as far as I understand is some hardcoded value someone assumed somewhere
        //    //the only place I can locate evidence of this is in the JoystickVRPN, line 68
        //    //joystickArray[i].tracker = string.Format("{0}{1}", DomeSeats.joystickDeviceNames, i);,
        //    ////so I am doing the same here, and I m manually copying the value for baseTrackerName from the provided script.

        //    item.AssignButtonData(string.Format("{0}{1}", baseTrackerName, SeatIndex), seatIndex);  
        //}
    }

    public void SubscribeToUserInput(int SeatIndex, int channel, bool state)
    {
        Debug.LogError(seatIndex + " : " + " : " + channel + " : " + state);

        //I only care for button state changes for my index
        if (SeatIndex == seatIndex)
        {
            Debug.Log(seatIndex + " : " + channel + " : " + state);
            buttonPad.SetButtonState(channel, state);
        }
        SendMessage("OnAnyUserInput", SendMessageOptions.DontRequireReceiver);
    }

    //smth to do at initialize and at button request
    public void ResetToInitialPosition(int seatIndex)
    {
        transform.position = UserAgentPositionInitializer.instance.CalculateInitialPosition(seatIndex);
    }

}

