using PlcSiemens.O;
using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.Upload;
using ByteBuffer = PlcSiemens.O.ByteBuffer;

namespace PlcSiemens.ProtocolHandle
{
    public class UploadHandle : IPacketHandle
    {
        public UploadRequest Request { get; set; }
        public UploadResponse Response { get; set; }

        public byte UploadID { get; set; }

        public ResultCode ResultCode { get; set; }

        public UploadHandle()
        {
            Request = new UploadRequest();
        }

        public void Handle(IIsoSender sender)
        {
            Request.UploadID = UploadID;

            Response = sender.IsoSend<UploadRequest, UploadResponse>(Request);

            ResultCode = Response.Header.Error;
            bool done = Response.Params.EoU == 0;
            ByteBuffer byteBuffer = ByteBuffer.Allocate();
            byteBuffer.Push(Response.Data.Datas);

            while (!done && ResultCode == ResultCode.OK)
            {
                Response = sender.IsoSend<UploadRequest, UploadResponse>(Request);
                ResultCode = Response.Header.Error;
                byteBuffer.Push(Response.Data.Datas);
                done = Response.Params.EoU == 0;
            }

            Request.UploadID = UploadID;
            Request.PduType = PduType.PduEndUpload;

            Response = sender.IsoSend<UploadRequest, UploadResponse>(Request);
            ResultCode = Response.Header.Error;
            done = Response.Params.EoU == 0;
        }
    }
}
