using Godot;


namespace Rokojori
{  
  [Tool][GlobalClass,Icon("res://addons/rokojori_action_library/Icons/NetworkManager.svg")]
  public partial class NetworkManager:Node
  {
    [Export]
    public NetworkBackend backend;

    NetworkNodeMemberReferences _references = new NetworkNodeMemberReferences(); 
    public NetworkNodeMemberReferences references => _references;

    ExtendedNetworkTransport _transport = new ExtendedNetworkTransport();
    public NetworkTransport transport => _transport;

    ExtendedNetworkSessionManager _sessionManager = new ExtendedNetworkSessionManager();
    public NetworkSessionManager sessionManager => _sessionManager;

    bool _initialized = false;

    [Export]
    public Action onStartedSession;

    [Export]
    public Action onSessionMemberJoined;

    [Export]
    public Action onSessionMemberLeft;

    public static NetworkManager Get()
    {
      return Unique<NetworkManager>.Get();
    }
    
    public static bool IsInSession 
    {
      get 
      {
        var nm = Get();

        if ( nm == null || nm.sessionManager == null )
        {
          return false;
        }

        return nm.sessionManager.isInSession;
      }
    }
    public static int ownSessionMemberIndex => Get().sessionManager.ownMemberIndex;
    public static int serverSessionMemberIndex =>Get().sessionManager.serverMemberIndex;


    public void Initialize()
    {
      if ( _initialized )
      {
        return;
      }

      if ( backend == null )
      {
        return;
      }

      RJLog.Log( "InitializeBackend:" );

      backend.InitializeBackend( this, _sessionManager, _transport );
      _initialized = true;
    }

    public override void _Process( double delta )
    {
      if ( sessionManager == null || ! sessionManager.isInSession  )
      {
        return;
      }

      _transport.ProcessQueuedMessages();
    }
  }
}