﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GarminFmiLib.Commands
{
    class CannedMessageCreator : RequestReply, ICannedMessageCreator
    {
        public CannedMessageCreator(ISerialPacketWriter writer)
            : base(writer, 0x0050, 0x0051, 8) { }

        public bool SetCannedMessage(int messageId, string message)
        {
            var messageIdBytes = BitConverter.GetBytes(messageId);
            var messageBytes = Encoding.ASCII.GetBytes(message.TrimExcess(50));
            var data = new List<byte>();
            data.AddRange(messageIdBytes); // id, 4 byte length
            data.AddRange(messageBytes); // text message, null terminated string, 50 bytes max

            succeeded = false;
            Write(data.ToArray());

            return succeeded;
        }

        protected override bool OnReplyReceived(FleetManagementProtocol fmp)
        {
            var data = fmp.Payload.ToArray();
            var messageId = BitConverter.ToInt32(data, 0);
            succeeded = BitConverter.ToBoolean(data, 4);
            // 3 bytes zero

            return true;
        }

        private bool succeeded;
    }
}