using PlcSiemens.O;
using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.Iso;

namespace PlcSiemens.ProtocolHandle
{
    public class IsoControlPduHandle : IPacketHandle
    {
        public int IsoPduSize { get; set; }
        public ushort SrcRef { get; set; }
        public ushort DstRef { get; set; }
        public ushort SrcTSap { get; set; }
        public ushort DstTSap { get; set; }

        public IList<IsoControlPdu> Requests { get; set; }
        public IList<IsoControlPdu> Responses { get; set; }

        public ResultCode ResultCode { get; set; }

        public void Handle(IIsoSender sender)
        {
            var request = new IsoControlPdu
            {
                IsoPduSize = IsoPduSize,
                SrcRef = SrcRef,
                DstRef = DstRef,
                SrcTSap = SrcTSap,
                DstTSap = DstTSap
            };

            Requests.Add(request);

            var response = sender.Send<IsoControlPdu, IsoControlPdu>(request);
            if (response == null)
            {
                ResultCode = ResultCode.ReadDataFalut;
                return;
            }

            if (CheckPdu(response, PduType.ConnConfirm) != 0) return;
            Responses.Add(response);
            ResultCode = ResultCode.OK;
        }

        public IsoControlPduHandle()
        {
            ResultCode = ResultCode.Unknown;
            Requests = new List<IsoControlPdu>();
            Responses = new List<IsoControlPdu>();
        }

        private int CheckPdu(IsoControlPdu pdu, PduType pduType)
        {
            int size = pdu.Tpkt.Length;
            if (size < 7 || size > StaticConst.IsoPayloadSize || pdu.Cotp.PduType != (byte)pduType)
                return (int)ErrorType.ErrIsoInvalidPdu;

            return (int)ErrorType.NoError;
        }
    }
}
