using System;
using System.Net;
using System.Threading;
using ActorCore;
using MrWu.Debug;
using NetWorkMessage;
using Server.Core;
using Server.Net;

namespace Server.Net
{
    /// <summary>
    /// ActorSession
    /// </summary>
    public class ActorSession : BaseSession
    {
        /// <summary>
        /// 实例Id
        /// </summary>
        public long InstanceId { get; set; }

        private static long IdGenerate = 0;
        
        private long GetInstanceId()
        {
            if (InstanceId >= long.MaxValue)
            {
                IdGenerate = 0;
            }

            IdGenerate++;
            
            return IdGenerate;
        }
        
        public ActorSession(long id, TService service, Action<long> disposedAction) : base(id, service, disposedAction)
        {
            InstanceId = GetInstanceId();
            Debug.Info($"创建实例:{InstanceId}");
        }

        public void Send(ActorId fromActorId,ActorId actorId, IMessage message)
        {
            this.LastSendTime = TimeInfo.Instance.ClientNow();
            Debug.Log($"Session Send {message} {Thread.CurrentThread.ManagedThreadId}");

            try
            {
                (uint opcode, MemoryBuffer memoryBuffer) =
                    MessageSerializeHelper.ToActorMemoryBuffer(Service, fromActorId, actorId, message);
                Service.Send(Id,memoryBuffer);
            }
            catch (Exception e)
            {
                Debug.Error($"回复消息报错？{e.ToString()} {message?.GetType()}");
            }
            
        }
    }
}