using PlcSiemens.O;
using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.ReadData;
using PlcSiemens.Protocol.WriteData;

namespace PlcSiemens.ProtocolHandle
{
    public class WriteMultiHandle : IPacketHandle
    {
        public ushort PduLength { get; set; }
        public List<DataItem> DataItem { get; set; }

        public ResultCode ResultCode { get; private set; }

        public void Handle(IIsoSender sender)
        {
            WriteRequest write = new WriteRequest();
            write.DataItems = DataItem;
            var res = sender.IsoSend<WriteRequest, WriteResponse>(write);

            ResultCode = res.Header.Error;
            if (ResultCode == ResultCode.OK)
            {
                for (int i = 0; i < res.Data.Length; i++)
                {
                    var reqItem = DataItem[i];
                    var resItem = res.Data[i];
                    reqItem.Err = (ResultCode)resItem.ReturnCode;
                    if (reqItem.Err == ResultCode.OKFF)
                        reqItem.Err = ResultCode.OK;
                }
            }
        }
    }
}
