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()
        {
            base.BeforeEncode();
            AddByte(0x02);
            AddByte(0x55);
            headerlength = AddByte(Type);
        }

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

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

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