using System;

namespace InABox.DigitalMatter
{
    public abstract class DMField : DMObject
    {
        private int _payloadaddress;
        public abstract byte Type { get; }

        public ushort Length { get; set; }

        protected override void BeforeEncode(IDMWriteBuffer buffer)
        {
            base.BeforeEncode(buffer);
            _payloadaddress = buffer.AddByte(Type);
        }

        protected override void AfterEncode(IDMWriteBuffer buffer)
        {
            base.AfterEncode(buffer);
            Length = buffer.BufferSize;
            buffer.InsertUInt16(_payloadaddress, Length);
        }

        protected override void BeforeDecode(IDMReadBuffer buffer)
        {
            base.BeforeDecode(buffer);
            int type = buffer.TakeByte();
            Length = buffer.PeekByte(0) == 255 ? buffer.TakeUInt16() : buffer.TakeByte();
        }

        public abstract bool IsValid();

        public virtual string Dump()
        {
            return BitConverter.ToString(new[] { Type });
        }
    }
}