#nullable enable

namespace Passer.Control.Core {

    public class NameMsg : IMessage {
        public const byte Id = 0x91; // 145
        public const byte length = 4;
        public byte networkId;
        public byte thingId;
        public byte len;
        public string? name = null;

        public NameMsg(byte networkId, Thing thing) {
            this.networkId = networkId;
            this.thingId = thing.id;
            this.name = thing.name;
        }
        public NameMsg(byte networkId, byte thingId, string name) {
            this.networkId = networkId;
            this.thingId = thingId;
            this.name = name;
        }
        public NameMsg(byte[] buffer) {
            byte ix = 1;
            this.networkId = buffer[ix++];
            this.thingId = buffer[ix++];
            int strlen = buffer[ix++];
            this.name = System.Text.Encoding.UTF8.GetString(buffer, (int)ix, strlen);
        }

        public override byte Serialize(ref byte[] buffer) {
            if (this.name == null)
                return 0;

            byte ix = 0;
            buffer[ix++] = NameMsg.Id;
            buffer[ix++] = this.networkId;
            buffer[ix++] = this.thingId;

            int nameLength = this.name.Length;

            buffer[ix++] = (byte)nameLength;
            for (int nameIx = 0; nameIx < nameLength; nameIx++)
                buffer[ix++] = (byte)this.name[nameIx];
            return ix;
        }
    }

}