using System;
using InABox.Core;

namespace InABox.Rpc
{
    [Serializable]
    public class RpcMessage : ISerializeBinary
    {
        public Guid Id { get; set; }
        public String Command { get; set; }
        public byte[] Payload { get; set; }
        public RpcError Error { get; set; }

        public override string ToString() => $"{Command} [{Error}]";

        public RpcMessage()
        {
            Id = Guid.NewGuid();
            Command = "";
            Payload = Array.Empty<byte>();
            Error = RpcError.NONE;
        }

        public RpcMessage(Guid id, string command, byte[] payload)
        {
            Id = id;
            Command = command;
            Payload = payload;
            Error = RpcError.NONE;
        }

        public void SerializeBinary(CoreBinaryWriter writer)
        {
            writer.Write(Id);
            writer.Write(Command);
            writer.WriteBinaryValue(Payload);
            writer.Write(Error.ToString());
        }

        public void DeserializeBinary(CoreBinaryReader reader)
        {
            Id = reader.ReadGuid();
            Command = reader.ReadString();
            Payload = reader.ReadBinaryValue<byte[]>();
            if (Enum.TryParse<RpcError>(reader.ReadString(), out var error))
                Error = error;
        }
    }
}