using System;
using System.Text;

namespace InABox.DigitalMatter
{
    public abstract class DMMessage : DMObject
    {
        private ushort headerlength;

        public abstract byte Type { get; }

        public ushort CheckSum { get; set; }

        protected override void BeforeEncode(IDMWriteBuffer buffer)
        {
            base.BeforeEncode(buffer);
            buffer.AddByte(0x02);
            buffer.AddByte(0x55);
            headerlength = buffer.AddByte(Type);
        }

        protected override void AfterEncode(IDMWriteBuffer buffer)
        {
            base.AfterEncode(buffer);
            var payloadlength = (ushort)(buffer.BufferSize - headerlength);
            buffer.InsertUInt16(headerlength, payloadlength);
        }

        protected override void BeforeDecode(IDMReadBuffer buffer)
        {
            base.BeforeDecode(buffer);
            var id1 = buffer.TakeByte();
            var id2 = buffer.TakeByte();
            var type = buffer.TakeByte();
            CheckSum = buffer.TakeUInt16();
        }

        public virtual byte[] Dump()
        {
            return Encoding.UTF8.GetBytes($"Type: {BitConverter.ToString(new[] { Type })}");
        }
    }
}