using IpcLibrary.Core;
using IpcLibrary.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace IpcLibrary.Serialization {
    /// <summary>
    /// 二进制序列化器实现（用于复杂对象）
    /// </summary>
    public class BinaryMessageSerializer : IMessageSerializer {
        public byte[] Serialize(object obj) {
            try {
                using var stream = new MemoryStream();
#pragma warning disable SYSLIB0011 // 类型或成员已过时
                var formatter = new BinaryFormatter();
#pragma warning restore SYSLIB0011 // 类型或成员已过时
                formatter.Serialize(stream, obj);
                return stream.ToArray();
            } catch (Exception ex) {
                throw new IPCException($"二进制序列化失败: {ex.Message}", ex);
            }
        }

        public T Deserialize<T>(byte[] data) {
            try {
                using var stream = new MemoryStream(data);
#pragma warning disable SYSLIB0011 // 类型或成员已过时
                var formatter = new BinaryFormatter();
#pragma warning restore SYSLIB0011 // 类型或成员已过时
                return (T)formatter.Deserialize(stream);
            } catch (Exception ex) {
                throw new IPCException($"二进制反序列化失败: {ex.Message}", ex);
            }
        }

        public object Deserialize(byte[] data, Type type) {
            try {
                using var stream = new MemoryStream(data);
#pragma warning disable SYSLIB0011 // 类型或成员已过时
                var formatter = new BinaryFormatter();
#pragma warning restore SYSLIB0011 // 类型或成员已过时
                return formatter.Deserialize(stream);
            } catch (Exception ex) {
                throw new IPCException($"二进制反序列化失败: {ex.Message}", ex);
            }
        }
    }
}
