using PlcSiemens.O;
using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.ListBlocks;

namespace PlcSiemens.ProtocolHandle
{
    public class DataBlockOfTypeHandle : IPacketHandle
    {
        public List<DataBlockOfTypeRequest> Requests { get; set; }
        public BlockType BlockType { get; set; }
        public List<DataBlockOfTypeResponse> Responses { get; set; }

        public ResultCode ResultCode { get; set; }

        public DataBlockOfTypeHandle()
        {
            ResultCode = ResultCode.Unknown;
            Requests = new List<DataBlockOfTypeRequest>();
            Responses = new List<DataBlockOfTypeResponse>();
        }

        public void Handle(IIsoSender sender)
        {
            var first = true;
            byte seq = 0x00;
            var done = false;
            do
            {
                var request = new DataBlockOfTypeRequest();
                request.First = first;
                request.Seq = seq;
                request.BlockType = BlockType;

                var response = sender.IsoSend<DataBlockOfTypeRequest, DataBlockOfTypeResponse>(request);

                ResultCode = response.Data.Ret;
                if (response.Params.Err == ResultCode.OK)
                {
                    if (response.Data.Ret == ResultCode.OKFF)
                    {
                        done = (response.Params.Rsvd & 0x00FF) == 0;

                        seq = response.Params.Seq;
                        Responses.Add(response);
                    }
                }
                if (ResultCode == ResultCode.OKFF)
                    ResultCode = ResultCode.OK;
                first = false;
            } while (!done && ResultCode == ResultCode.OK);
        }
    }
}
