using System;
using System.Buffers;
using System.ComponentModel;
using System.IO;
using System.Runtime.Remoting.Contexts;
using MessagePack;
using Server.Net;

namespace Server.Core
{
    public class MessagePackHelper
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static byte[] Serialize(object message)
        {
            if (message is ISupportInitialize supportInitialize)
            {
                supportInitialize.BeginInit();
            }

            return MessagePackSerializer.Serialize(message.GetType(), message);
        }

        public static void Serialize(object message, MemoryStream stream)
        {
            if (message is ISupportInitialize supportInitialize)
            {
                supportInitialize.BeginInit();
            }

            MessagePackSerializer.Serialize(stream, message);
        }

        public static T Deserialize<T>(byte[] bytes)
        {
            return (T)Deserialize(typeof(T), bytes);
        }

        public static T Deserialize<T>(byte[] bytes, int index, int count)
        {
            return (T)Deserialize(typeof(T), bytes, index, count);
        }

        public static object Deserialize(Type type,byte[] bytes)
        {
            return Deserialize(type, bytes, 0, bytes.Length);
        }
        
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="bytes"></param>
        /// <param name="index"></param>
        /// <param name="count"></param>
        public static object Deserialize(Type type, byte[] bytes, int index, int count)
        {
            return Deserialize(type, bytes.AsMemory(index, count));
        }
        
        public static object Deserialize(Type type, Memory<byte> bytes)
        {
            object o = MessagePackSerializer.Deserialize(type,bytes);
            if (o is ISupportInitialize supportInitialize)
            {
                supportInitialize.EndInit();
            }

            return o;
        }
        
        
        
    }
}