// Created with MonoDevelop
//
//    Copyright (C) 2019 Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Runtime.Serialization;

using Hiperscan.Unix;


namespace Hiperscan.SGS.SgsNt.Protocol
{
    abstract partial class BaseProtocol
    {
        public class Response : Hiperscan.SGS.SgsNt.Protocol.BaseProtocol.Frame
        {
            public Response(byte[] buf, Type payload_data_type) : base(buf, payload_data_type)
            {
            }

            public Errno Check(Command command)
            {
                if (this.PayloadCmd1 != command.PayloadCmd1 || this.PayloadCmd2 != command.PayloadCmd2)
                {
                    string msg = string.Format(Catalog.GetString("Unexpected device response (Command ID): {0}{1}"), this.PayloadCmd1, this.PayloadCmd2);
                    Console.WriteLine(msg);
                    throw new Exception(msg);
                }

                if (this.ComputeCrc32() != this.Checksum)
                    throw new ChecksumException(Catalog.GetString("Invalid device response (Checksum)."));

                if (this.HeaderErrno == Errno.Success && 
                    this.HasPayloadData != command.IsDataRequest)
                    throw new Exception(Catalog.GetString("Unexpected device response (Payload data length)."));

                return this.HeaderErrno;
            }

            public override string ToString()
            {
                return "[Response]" + base.ToString();
            }

            public bool HasPayloadData 
            { 
                get
                {
                    return this.PayloadLength > 0;
                }
            }
        }
    }

    [Serializable]
    public class ChecksumException : Exception
    {
        public ChecksumException()
        {
        }

        public ChecksumException(string message) : base(message)
        {
        }

        public ChecksumException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected ChecksumException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}