using System.Text;

namespace Hcs.Broker.MessageCapturer
{
    /// <summary>
    /// Реализация захвата содержимого отправляемых и принимаемых SOAP сообщений,
    /// которая хранит данные в памяти
    /// </summary>
    public class MemoryMessageCapturer : IMessageCapturer
    {
        private readonly MemoryStream messageCaptureStream;
        private readonly StreamWriter messageCaptureWriter;

        public MemoryMessageCapturer()
        {
            messageCaptureStream = new MemoryStream();
            messageCaptureWriter = new StreamWriter(messageCaptureStream, Encoding.UTF8);
        }

        public void CaptureMessage(bool sent, string messageBody)
        {
            if (messageCaptureStream.Position > 0)
            {
                messageCaptureWriter.WriteLine("");
            }

            messageCaptureWriter.Write("<!--");
            messageCaptureWriter.Write(sent ? "SENT " : "RECEIVED ");
            messageCaptureWriter.Write(DateTime.Now.ToString());
            messageCaptureWriter.WriteLine("-->");
            messageCaptureWriter.Write(messageBody);
            messageCaptureWriter.Flush();
        }

        public byte[] GetData()
        {
            var buf = messageCaptureStream.GetBuffer();
            var size = (int)messageCaptureStream.Length;
            var data = new byte[size];
            Buffer.BlockCopy(buf, 0, data, 0, size);
            return data;
        }

        public override string ToString()
        {
            return Encoding.UTF8.GetString(GetData());
        }
    }
}
