using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace iSTP_Embedded
{
    public partial class EmbeddedPacket
    {
        private Byte[] BinWriteBuffer = new Byte[28];

        public bool WriteToStream(Stream OutStream)
        {
            bool retVal = false;
            try
            {
                BinaryConverter.GetBytes(BinWriteBuffer, 0, 0x23232323); // header '####'
                BinaryConverter.GetBytes(BinWriteBuffer, 4, MsgNumber);
                BinaryConverter.GetBytes(BinWriteBuffer, 8, MsgTimeStamp);
                BinaryConverter.GetBytes(BinWriteBuffer, 16, MsgType);
                BinaryConverter.GetBytes(BinWriteBuffer, 20, MsgID);
                BinaryConverter.GetBytes(BinWriteBuffer, 24, MsgLength);
                OutStream.Write(BinWriteBuffer, 0, 28);

                if (MsgLength > 0)
                {
                    OutStream.Write(MsgData, 0, MsgLength);
                }

                MsgChecksum = CalcCRC32();
                BinaryConverter.GetBytes(BinWriteBuffer, 0, MsgChecksum);
                OutStream.Write(BinWriteBuffer, 0, 4);
                
                retVal = true;
            }
            catch (IOException ex)
            {
                EmbeddedError.Add("EmbeddedPacketWriter.cs", "Error during comunication", ex.ToString(), true);
            }
            return retVal;
        }

        public void DumpPacket(Stream OutStream)
        {
            try
            {
                OutStream.Write(Encoding.ASCII.GetBytes(DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss.f]")), 0, 23);
                Byte[] writeBuffer = new byte[28];
                BinaryConverter.GetBytes(writeBuffer, 0, 0x23232323); // header '####'
                BinaryConverter.GetBytes(writeBuffer, 4, MsgNumber);
                BinaryConverter.GetBytes(writeBuffer, 8, MsgTimeStamp);
                BinaryConverter.GetBytes(writeBuffer, 16, MsgType);
                BinaryConverter.GetBytes(writeBuffer, 20, MsgID);
                BinaryConverter.GetBytes(writeBuffer, 24, MsgLength);
                OutStream.Write(writeBuffer, 0, 28);

                if (MsgLength > 0)
                {
                    OutStream.Write(MsgData, 0, MsgLength);
                }

                BinaryConverter.GetBytes(writeBuffer, 0, MsgChecksum);
                OutStream.Write(writeBuffer, 0, 4);
            }
            catch (IOException ex)
            {
                EmbeddedError.Add("EmbeddedPacketWriter.cs", "Error during comunication", ex.ToString(), true);
            }
        }
    }
}
