//  
//   Rebex Sample Code License
// 
//   Copyright 2026, REBEX CR s.r.o.
//   All rights reserved.
//   https://www.rebex.net/
// 
//   Permission to use, copy, modify, and/or distribute this software for any
//   purpose with or without fee is hereby granted.
// 
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//   OTHER DEALINGS IN THE SOFTWARE.
// 

using System;
using System.Text;

namespace Rebex.Samples
{
    /// <summary>
    /// Very simple HTTP parser.
    /// This is a sample code that only implements HTTP partially and is not suitable for general use.
    /// </summary>
    public class SimpleHttpParser
    {
        private const string END_OF_HTTP_HEADERS = "\r\n\r\n";
        private readonly StringBuilder _httpString;
        private bool _headersFound;

        public SimpleHttpParser()
        {
            _httpString = new StringBuilder();
            _headersFound = false;
        }

        public SimpleHttpResponse ProcessBytes(ArraySegment<byte> buffer, out int processedBytes)
        {
            processedBytes = 0;
            if (_headersFound || buffer.Count == 0)
            {
                return null;
            }

            processedBytes = buffer.Count;

            string currentString = Encoding.ASCII.GetString(buffer.Array, buffer.Offset, buffer.Count);
            int endOfHttpIndex = currentString.IndexOf(END_OF_HTTP_HEADERS, StringComparison.Ordinal);
            if (endOfHttpIndex > -1)
            {
                if (!currentString.EndsWith(END_OF_HTTP_HEADERS, StringComparison.Ordinal))
                {
                    var lastCharIndexInEndOfHttpString = endOfHttpIndex + END_OF_HTTP_HEADERS.Length;
                    currentString = currentString.Substring(0, lastCharIndexInEndOfHttpString);
                    processedBytes = lastCharIndexInEndOfHttpString;
                }
            }

            _httpString.Append(currentString);
            string currentHeaders = _httpString.ToString();
            if (endOfHttpIndex > -1 || currentHeaders.IndexOf(END_OF_HTTP_HEADERS, StringComparison.Ordinal) > -1)
            {
                _headersFound = true;
                return new SimpleHttpResponse(currentHeaders.Replace(END_OF_HTTP_HEADERS, string.Empty));
            }

            return null;
        }
    }
}
