using Godot;
using System.Collections.Generic;


namespace Rokojori
{  
  public class NetworkSessionManager
  { 
    protected bool _isInSession = false;
    public bool isInSession => _isInSession;
    
    protected string _sessionName = null;
    public string sessionName => _sessionName;

    protected int _serverMemberIndex = 0;
    public int serverMemberIndex => _serverMemberIndex;

    protected int _ownMemberIndex = -1;    
    public int ownMemberIndex => _ownMemberIndex;    

    public bool isServer => ownMemberIndex == serverMemberIndex;
    
    protected List<NetworkSessionMember> _sessionMembers = new List<NetworkSessionMember>();

    public EventSlot<NetworkSessionEvent> onSessionEntered = new EventSlot<NetworkSessionEvent>();
    public EventSlot<NetworkSessionEvent> onSessionLeft = new EventSlot<NetworkSessionEvent>();


    public void StartSession( NetworkSessionRequest sessionRequest )
    {
      var nm = Unique<NetworkManager>.Get();
      
      if ( nm.backend == null )
      {
        return;
      }

      RJLog.Log( "StartSession" );
      nm.backend.StartSession( sessionRequest );
    }

    
    public void JoinSession( NetworkSessionRequest sessionRequest )
    {
      var nm = Unique<NetworkManager>.Get();
      
      if ( nm.backend == null )
      {
        return;
      }

      RJLog.Log( "JoinSession" );

      nm.backend.JoinSession( sessionRequest );
    }

    public void LeaveSession()
    {
      var nm = Unique<NetworkManager>.Get();
      
      if ( nm.backend == null )
      {
        return;
      }

      nm.backend.LeaveSession();
    }
  }

  public class ExtendedNetworkSessionManager:NetworkSessionManager
  { 
    public void SetInSessionState( bool state = true )
    {
      _isInSession = state;
    }

    public void AddMember( NetworkSessionMember member )
    {
      _sessionMembers.Add( member );
      
      var nse = new NetworkSessionEvent();
      nse.memberIndex = member.index;

      onSessionEntered.DispatchEvent( nse );
    }

    public void RemoveMember( long id )
    {
      var index = _sessionMembers.FindIndex( m => m.index == id );

      if ( index == -1 )
      {
        return;
      }

      _sessionMembers.RemoveAt( index );

      var nse = new NetworkSessionEvent();
      nse.memberIndex = id;

      onSessionLeft.DispatchEvent( nse );
    }
  }
}