using PlcSiemens.Core.Extension;
using PlcSiemens.O;
using PlcSiemens.Protocol.Common;

namespace PlcSiemens.Protocol.Security
{
    public class DataSecurityRequest
    {
        public byte Ret;    // 0xFF for request
        public byte Ts;     // 0x09 Transport size
        public ushort DLen;   // Data len  : 8 bytes
        public char[] Pwd; // Password encoded into "AG" format 8

        public ushort PacketLength
        { get { return 0x0C; } }

        public void Build(params char[] value)
        {
            if (value.IsNotEmpty())
            {
                Ts = (byte)TsType.TsResOctet;
                Ret = 0xFF;
                Pwd = value;
                DLen = 0x0008;
            }
            else
            {
                Ts = 0x00;
                Ret = 0x0A;
                DLen = 0x0000;
            }
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(Ret);
            buffer.Push(Ts);
            buffer.Push(DLen);
            if (DLen == 0) return;
            Pwd[0] = (char)(Pwd[0] ^ 0x55);
            Pwd[1] = (char)(Pwd[1] ^ 0x55);
            for (var i = 2; i < 8; i++)
            {
                Pwd[i] = (char)(Pwd[i] ^ 0x55 ^ Pwd[i - 2]);
            }
            ;

            Pwd.ForEach(t => buffer.Push((byte)t));
        }
    }
}
