using PlcSiemens.O;
using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.Negotiate;

namespace PlcSiemens.ProtocolHandle
{
    public class NegotiateHandle : IPacketHandle
    {
        public ushort PduRequest { get; set; }
        public IList<NegotiateRequest> Requests { get; set; }
        public IList<NegotiateResponse> Responses { get; set; }
        public ResultCode ResultCode { get; set; }

        public NegotiateHandle()
        {
            ResultCode = ResultCode.Unknown;
            PduRequest = 480;
            Requests = new List<NegotiateRequest>();
            Responses = new List<NegotiateResponse>();
        }

        public void Handle(IIsoSender sender)
        {
            var negotiateRequest = new NegotiateRequest();
            negotiateRequest.PduRequestLength = PduRequest;

            Requests.Add(negotiateRequest);
            var response = sender.IsoSend<NegotiateRequest, NegotiateResponse>(negotiateRequest);
            if (response == null)
            {
                ResultCode = ResultCode.PduConfirmFault;
                return;
            }
            ResultCode = response.Header.Error;
            if (ResultCode == ResultCode.OK)
                Responses.Add(response);
        }
    }
}
