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

namespace Server
{
    public class MainActor : Actor
    {
        public override SchedulerType SchedulerType => SchedulerType.Main;

        public override MailBoxType MailBoxType => MailBoxType.UnOrderedMessage;
        
        public static ActorId MainActorId
        {
            get;
            private set;
        }

        protected virtual bool IsOrderMessage => true; 

        public MainActor(byte moduleId, byte nodeNum) : base(moduleId, nodeNum, ActorTypeId.Main)
        {
            MainActorId = new ActorId(moduleId, nodeNum, ActorTypeId.Main);
        }

        public override void RegisterHandle()
        {
            this.RegisterMessageHandle(typeof(ClientMessage),OuterMessageHandle);
            this.RegisterMessageHandle(typeof(UserPropChangeMessage),OnUserPropChangeMessage);
            this.RegisterMessageHandle(typeof(UserCurrencyChangeMessage),OnUserCurrencyChangeMessage);
            this.RegisterRPCHandle(typeof(RpcTestRequest),OnRpcTestRequest);
            MessageDispatcher.Instance.Start(IsOrderMessage,CoroutineLockManager);
        }

        private Task OuterMessageHandle(ActorId fromActorId,IMessage message)
        {
            if (message is ClientMessage clientMessage)
            {
                GameMessageDispatcher.Instance.Dispatch(clientMessage.OpCode, clientMessage);
            }

            return Task.CompletedTask;
        }
        
        private Task OnUserPropChangeMessage(ActorId fromActorId,IMessage message)
        {
            if (message is UserPropChangeMessage userPropChangeMessage)
            {
                GameDispatcher.Instance.Dispatch(GameMsgId.UserPropChange,userPropChangeMessage);
            }
            
            return Task.CompletedTask;
        }

        private Task OnUserCurrencyChangeMessage(ActorId formActorId, IMessage message)
        {
            if (message is UserCurrencyChangeMessage userCurrencyChangeMessage)
            {
                GameDispatcher.Instance.Dispatch(GameMsgId.UserCurrencyChange,userCurrencyChangeMessage);
            }

            return Task.CompletedTask;
        }

        private Task OnRpcTestRequest(ActorId fromActorId,IRequest request,IResponse response)
        {
            if (request is RpcTestRequest rpcTestRequest && response is RpcTestResponse rpcTestResponse)
            {
                rpcTestResponse.Id = rpcTestRequest.Id;
            }
            return Task.CompletedTask;
        }

        protected override void Update()
        {
            if (UserSessionManager.Instance != null)
            {
                UserSessionManager.Instance.Update();
            }
            
            //处理客户端消息
            MessageDispatcher.Instance.Handle();
        }

        public override void Dispose()
        {
            base.Dispose();
        }
    }
}