using Fusion;
using Fusion.Addons.ConnectionManagerAddon;
using Fusion.XR.Host.Rig;
using Photon.Voice.Unity;
using RTLTMPro;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using UnityEngine.XR;

public class playerManager : NetworkBehaviour
{
    public static playerManager instance;
    public int selectedMic;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        instance = this;
        selectedMic = PlayerPrefs.GetInt("Mic", 0);
        speaker = GetComponentInChildren<Speaker>();

        rightController = InputDevices.GetDeviceAtXRNode(XRNode.RightHand);
        leftController = InputDevices.GetDeviceAtXRNode(XRNode.LeftHand);
    }
    private UnityEngine.XR.InputDevice rightController;
    private UnityEngine.XR.InputDevice leftController;



    void ChangeLayerRecursively(GameObject obj, string newLayer)
    {
        obj.layer = LayerMask.NameToLayer(newLayer);

        foreach (Transform child in obj.transform)
        {
            ChangeLayerRecursively(child.gameObject, newLayer);
        }
    }
    Speaker speaker;
    // Update is called once per frame
    void Update()
    {
      //  print(player.PlayerId + "==" + Runner.LocalPlayer.PlayerId);
      if(Runner.IsConnectedToServer)
        if (Object.InputAuthority.PlayerId==Runner.LocalPlayer.PlayerId)
        {
            PlayerId = EN.instance.SelectedUser.id.ToString();
            Nickname = EN.instance.Me.first_name + " " + EN.instance.Me.last_name;
            RPC_SetPlayerName(PlayerId.Value);
        }
       // if(Object.HasInputAuthority)
         //   RPC_RequestCharacterSpawn(player);


        NetworkObject networkObject = GetComponent<NetworkObject>();

        // اگر آبجکت دارای State Authority باشد (یعنی این بازیکن صاحب آن است)
        if (networkObject != null && networkObject.HasInputAuthority)
            ChangeLayerRecursively(gameObject, "invisible");
        if (speaker == null)
            speaker = GetComponentInChildren<Speaker>();
        else
            transform.Find("Headset/HeadsetVisuals/PhotonDummy/board/back").GetComponent<Image>().color= speaker.IsPlaying?Color.green:Color.grey;
            transform.Find("Headset/HeadsetVisuals/PhotonDummy/board/back1").GetComponent<Image>().color= speaker.IsPlaying?Color.green:Color.grey;
        transform.Find("Headset/HeadsetVisuals/PhotonDummy/board/name").GetComponent<RTLTextMeshPro>().text = Nickname.ToString();
        for (int i = 0; i < EN.instance.users.Count; i++)
            if (transform.Find(i.ToString()))
            if (i != Id)
                transform.Find(i.ToString()).gameObject.SetActive(false);
            else
                    transform.Find(i.ToString()).gameObject.SetActive(true);
        float gripValue;
        if(selectedMic==0)
        ConnectionManager.instance.GetComponentInChildren<Recorder>().TransmitEnabled = true;
        else if (selectedMic == 1)
            ConnectionManager.instance.GetComponentInChildren<Recorder>().TransmitEnabled = leftController.TryGetFeatureValue(UnityEngine.XR.CommonUsages.primaryButton, out bool isPressed) && isPressed;
        else
            ConnectionManager.instance.GetComponentInChildren<Recorder>().TransmitEnabled = false;
        //(rightController.TryGetFeatureValue(UnityEngine.XR.CommonUsages.grip, out gripValue) && gripValue > 0.5f);
        try
            {

                Id = int.Parse(PlayerId.Value);
            }
            catch
            {

            }

    }
    // [Networked]
    //public NetworkString<_16> PlayerName { get; set; } // نام کاربر با حداکثر 16 کاراکتر

    [Networked]
    public NetworkString<_16> PlayerId { get; set; } // نام کاربر با حداکثر 16 کاراکتر

    [Networked, OnChangedRender(nameof(NicknameChanged))]
    public NetworkString<_32> Nickname { get; set; }

    private void NicknameChanged()
    {
        if (transform.Find("Headset/HeadsetVisuals/PhotonDummy/board/name"))
        {
            transform.Find("Headset/HeadsetVisuals/PhotonDummy/board/name").GetComponent<RTLTextMeshPro>().text = Nickname.ToString();
        }
    }

    [Rpc(RpcSources.All, RpcTargets.All)]
    public void RPC_SetPlayerName(string id)
    {

        PlayerId = id;
       // print("I Recevie " + id);
 

    }
    public int Id;
    public PlayerRef player;


 
}
