using System.Net;
using System.Threading.Tasks;
using ActorCore;
using NetWorkMessage;
using Server.Net;

namespace Server
{
    /// <summary>
    /// 用户网络
    /// </summary>
    public class UserNetActor : Actor
    {
        public override SchedulerType SchedulerType => SchedulerType.Thread;

        public override MailBoxType MailBoxType => MailBoxType.UnOrderedMessage;

        private UserNetSessionManager _userNetSessionManager;
        
        public int ConnectCnt
        {
            get
            {
                return _userNetSessionManager.ConnectCnt;
            }
        }
        
        public UserNetActor(byte moduleId, byte nodeNum,IPEndPoint ipEndPoint) : base(moduleId, nodeNum, ActorTypeId.UserNet)
        {
            _userNetSessionManager = new UserNetSessionManager();
            _userNetSessionManager.Start(ipEndPoint);
        }

        public override void RegisterHandle()
        {
            this.RegisterMessageHandle(typeof(UserNetSendMessage), HandleUserNetSend);
            this.RegisterMessageHandle(typeof(UserNetForceFinMessage), HandleUserNetForceFin);
            
        }

        public bool IsPrintLog;

        protected override void Update()
        {
            if (IsPrintLog)
            {
                IsPrintLog = false;
                _userNetSessionManager.Log();
            }
            
            _userNetSessionManager.Update();
            base.Update();
        }

        public override void Dispose()
        {
            _userNetSessionManager.Dispose();
            base.Dispose();
        }
        
        private Task HandleUserNetSend(ActorId fromActorId, IMessage message)
        {
            if (message is UserNetSendMessage userNetSendMessage)
            {
                _userNetSessionManager.Send2Router(userNetSendMessage.Id,userNetSendMessage.InstanceId,userNetSendMessage.MessageObject);
            }
            return Task.CompletedTask;
        }

        private Task HandleUserNetForceFin(ActorId fromActorId, IMessage message)
        {
            if (message is UserNetForceFinMessage forceFinMessage)
            {
                _userNetSessionManager.ForceDisConnect(forceFinMessage.Id,forceFinMessage.InstanceId,forceFinMessage.FinCode);
            }

            return Task.CompletedTask;
        }
    }
}