using System.Collections.Generic;
using CrazyGames;
using Photon.Pun;

public class JoinListenerSingleton : MonoBehaviourPunCallbacks
{
    public static JoinListenerSingleton Instance { get; private set; }

    private string _pendingRoomName;

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
        CrazySDK.Game.AddJoinRoomListener(JoinRoomListener);
        Logger.Log("Join room listener added");
    }

    // similar to HandleInitialInviteParams in LobbyScene
    // you should consider showing a confirmation popup to the user before joining the room
    // it may happen that the user is in a match and receives an invite, and clicks it by mistake, thus trigger the join room listener
    private void JoinRoomListener(Dictionary<string, string> inviteParams)
    {
        if (inviteParams.TryGetValue("regionId", out var regionId))
        {
            if (PhotonNetwork.NetworkingClient.CloudRegion != regionId)
            {
                Logger.LogError(
                    "Invite params specify region "
                        + regionId
                        + " but current Photon region is "
                        + PhotonNetwork.NetworkingClient.CloudRegion
                        + ", not joining room"
                );
                return;
            }
        }

        if (inviteParams.TryGetValue("roomName", out var roomName))
        {
            Logger.Log("Join room listener triggered, joining room: " + roomName);

            if (PhotonNetwork.InRoom)
            {
                _pendingRoomName = roomName;
                PhotonNetwork.LeaveRoom();
            }
            else
            {
                PhotonNetwork.JoinRoom(roomName);
            }
        }
    }

    public override void OnConnectedToMaster()
    {
        if (_pendingRoomName != null)
        {
            var roomName = _pendingRoomName;
            _pendingRoomName = null;
            Logger.Log("Reconnected to Master Server, now joining: " + roomName);
            PhotonNetwork.JoinRoom(roomName);
        }
    }
}
