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()
        {
            base.BeforeEncode();
            _payloadaddress = AddByte(Type);
        }

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

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

        public abstract bool IsValid();

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