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

namespace PlcSiemens.Protocol.Security
{
    public class SetPasswordRequest : IBuildRequest
    {
        public HeaderPacket Header { get; set; }
        public ParamsRequest Params { get; set; }
        public DataSecurityRequest Data { get; set; }

        public string Password { get; set; }

        public SetPasswordRequest()
        {
            Header = new HeaderPacket();
            Params = new ParamsRequest();
            Data = new DataSecurityRequest();
        }

        public void Build()
        {
            Header.Build(PduType.Userdata, Params.PacketLength, Data.PacketLength);
            if (Password.IsNotEmpty())
            {
                Header.Build(PduType.Userdata, Params.PacketLength, Data.PacketLength);
                Params.Build(true, 0x00, GrType.GrSecurity, PduFuncType.SFunEnterPwd);
                Data.Build(Password.PadRight(8, ' ').ToCharArray());
            }
            else
            {
                Header.Build(PduType.Userdata, Params.PacketLength, (ushort)(Data.PacketLength - 8));
                Params.Build(true, 0x00, GrType.GrSecurity, PduFuncType.SFunCancelPwd);
            }
            Params.Uk = 0x11;
        }

        public ByteBuffer GetBuffer()
        {
            ByteBuffer buffer = ByteBuffer.Allocate();
            Header.GetByteBuffer(buffer);
            Params.GetByteBuffer(buffer);
            Data.GetByteBuffer(buffer);
            return buffer;
        }
    }
}
