using StandardScene.Magnetic.Protocol;
using System;

namespace StandardScene.Magnetic.Tests.TestHelpers
{
    internal static class Fass2TestFrameBuilder
    {
        public static byte[] BuildStateFrame(
            ushort car,
            byte state,
            ushort nodeId,
            ulong taskId = 0,
            byte command = 0)
        {
            var frame = new byte[Fass2Protocol.StateFrameLength];
            frame[0] = Fass2Protocol.Begin;
            frame[1] = command;
            WriteUInt16(frame, 2, car);
            WriteUInt16(frame, 4, 1200);
            WriteUInt16(frame, 6, 800);
            frame[28] = 100;
            frame[29] = 100;
            frame[36] = state;
            WriteUInt64(frame, 45, taskId);

            var node = new Fass2NodeMessage
            {
                Node = nodeId,
                StartStop = 1,
                Distance = 500,
                Speed = 120
            };
            Buffer.BlockCopy(node.ToBytes(), 0, frame, 53, 25);

            frame[98] = Fass2Protocol.Xor(frame, 1, 97);
            frame[99] = Fass2Protocol.End;
            return frame;
        }

        public static string ToHex(byte[] bytes)
        {
            if (bytes == null)
            {
                return string.Empty;
            }

            var parts = new string[bytes.Length];
            for (var i = 0; i < bytes.Length; i++)
            {
                parts[i] = bytes[i].ToString("X2");
            }

            return string.Join(" ", parts);
        }

        private static void WriteUInt16(byte[] buffer, int offset, ushort value)
        {
            var bytes = BitConverter.GetBytes(value);
            buffer[offset] = bytes[0];
            buffer[offset + 1] = bytes[1];
        }

        private static void WriteUInt64(byte[] buffer, int offset, ulong value)
        {
            var bytes = BitConverter.GetBytes(value);
            Buffer.BlockCopy(bytes, 0, buffer, offset, 8);
        }
    }
}
