/*******************************************************************************
 * Copyright (c) 2014, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <netplus/socket.h>
#include <netplus/eventapi.h>
#include <netplus/threadpool.h>
#include <atomic>
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>

#include "http.h"
#include "qpack.h"
#include "exception.h"

#pragma once

namespace cmdplus {
    class CmdController;    
}

namespace libhttppp {
    class HttpEvent : public netplus::event {
    public:
        // h2OffloadThreads: when non-zero, spins up a background thread pool
        // (see shouldOffloadH2Dispatch) that lets HTTP/2 streams whose
        // RequestEvent does slow, blocking work (e.g. a backend network
        // round-trip) run without blocking every other stream multiplexed
        // on the same connection. Zero (the default) preserves the original
        // fully-synchronous H2 dispatch behavior for every existing caller.
        HttpEvent(std::vector<netplus::socket*> serversocket,int timeout = 1000,
                  size_t h2OffloadThreads = 0);

        // Return true to have this stream's RequestEvent run on the H2
        // offload thread pool instead of inline in the frame-processing
        // loop. Called right after the per-stream request's headers have
        // been parsed (so :path/:method are already available), before
        // RequestEvent runs. Defaults to false — every route stays on the
        // original synchronous path unless a subclass opts a specific
        // route in. Has no effect if h2OffloadThreads is 0.
        virtual bool shouldOffloadH2Dispatch(HttpRequest &tempreq, uint32_t streamId) const {
            return false;
        }

        virtual void RequestEvent(HttpRequest &curreq,const int tid,ULONG_PTR args);
        virtual void ResponseEvent(HttpRequest &curreq,const int tid,ULONG_PTR args);
        virtual void ConnectEvent(HttpRequest &curreq,const int tid,ULONG_PTR args);
        virtual void DisconnectEvent(HttpRequest &curreq,const int tid,ULONG_PTR args);

        virtual bool Http2RequestEvent(netplus::con &curcon,
                                       const int tid,
                                       ULONG_PTR args,
                                       const std::string &alpn,
                                       const netplus::ssl::FramingCallback &frame_cb);
        virtual void Http3StreamEvent(netplus::socket *sock,
                                      uint64_t stream_id,
                                      const std::vector<uint8_t> &data,
                                      bool fin);

        // Streaming body callbacks for H2/H3.
        // Called when headers are complete for a body-bearing stream.
        // Return true to handle body data via onH2DataChunk/onH3DataChunk
        // instead of buffering the full body.
        virtual bool onH2StreamHeaders(HttpRequest &conn, uint32_t streamId,
                                       const std::vector<hpack::HeaderField> &headers);
        virtual bool onH3StreamHeaders(netplus::socket *sock, uint64_t streamId,
                                       const std::vector<qpack::HeaderField> &headers);

        // Called for each body data chunk when streaming is enabled.
        // endStream/fin: true on the last chunk.
        virtual void onH2DataChunk(HttpRequest &conn, uint32_t streamId,
                                   const char *data, size_t len, bool endStream,
                                   std::string &h2out, const int tid, ULONG_PTR args);
        virtual void onH3DataChunk(netplus::socket *sock, uint64_t streamId,
                                   const char *data, size_t len, bool fin);

    protected:
        // Helpers for sending a complete response on an H2/H3 stream.
        void sendH2StreamResponse(std::string &h2out, uint32_t streamId,
                                  uint16_t status, const std::string &contentType,
                                  const std::string &body);
        void sendH3StreamResponse(netplus::socket *sock, uint64_t streamId,
                                  uint16_t status, const std::string &contentType,
                                  const std::string &body);
        virtual void CreateConnection(std::shared_ptr<netplus::con> &res);

        virtual void RequestEvent(netplus::con &curcon, const int tid, ULONG_PTR args);
        virtual void ResponseEvent(netplus::con &curcon,const int tid,ULONG_PTR args);
        virtual void ConnectEvent(netplus::con &curcon,const int tid,ULONG_PTR args);
        virtual void DisconnectEvent(netplus::con &curcon,const int tid,ULONG_PTR args);

        std::string _altSvcH3;   // Alt-Svc value for HTTP/3 advertisement

        // TLS session cache — shared across all accepted SSL connections
        // to enable abbreviated TLS 1.2 handshakes on client reconnection.
        netplus::TlsSessionCache _tlsSessionCache;
    private:
        // Per-stream state for HTTP/3: accumulates data and supports
        // incremental H3 frame parsing for streaming body callbacks.
        struct H3StreamState {
            std::vector<uint8_t> data;
            bool headersParsed = false;
            bool streaming = false;
            size_t parseOffset = 0;
        };
        std::mutex                            _h3BufferMutex;
        std::map<uint64_t, H3StreamState>     _h3StreamStates;
        std::atomic<int>                      _h3NextTid{0};

        // Non-null only when h2OffloadThreads > 0 was passed to the
        // constructor. See shouldOffloadH2Dispatch / _dispatchH2Stream.
        std::unique_ptr<netplus::ThreadPool>  _h2DispatchPool;

        // Returns true if the stream was handed off to the background
        // offload pool instead of being finished synchronously — callers
        // must treat that as "progress" for reprocess-loop purposes even
        // though it leaves `out` unchanged, since the frame was still
        // consumed from RecvData either way.
        bool _dispatchH2Stream(HttpRequest &cureq, std::string &out,
                               uint32_t sid,
                               const std::vector<hpack::HeaderField> &decoded,
                               const std::string &reqBody,
                               const int tid, ULONG_PTR args);
        // The part of stream dispatch that must run on the connection's
        // owning thread: extracts the plugin's :res-* response headers off
        // an already-completed tempreq, HPACK-encodes them, and frames the
        // response (or sets up activeStreams for a streaming response).
        // Shared by both the synchronous path and the offload-completion
        // path so they behave identically once RequestEvent has returned.
        void _finishH2Dispatch(HttpRequest &cureq, std::string &out,
                               uint32_t sid,
                               std::unique_ptr<HttpRequest> tempreq,
                               const int tid, ULONG_PTR args);
        // Factored out of the synchronous dispatch loop's immediate-flush
        // step so the offload-completion path (which has no "loop" to fall
        // through to) can reuse the exact same send behavior.
        bool _flushSendDataNow(HttpRequest &cureq);
        void _resumeH2Streams(HttpRequest &cureq, std::string &out,
                              const int tid, ULONG_PTR args);
        void _reapStalledH2Streams(HttpRequest &cureq, std::string &out);
    };

    class HttpD {
    public:
        HttpD(int argc, char** argv);
        HttpD(const std::string &httpaddr, int port, int maxconnections, const std::string &sslcertpath, const  std::string &sslkeypath, const std::string &sslpassword = "");
        ~HttpD();
        std::vector<netplus::socket*> getServerSockets();

        // Reload SSL certificates from file(s). Updates all ssl/quic server sockets.
        bool reloadCertificates(const std::string &certpath, const std::string &keypath, const std::string &password = "");
    protected:
        void                        FileServer();
    private:

        bool             _fileServer;
        std::vector<std::unique_ptr<netplus::socket>> _ServerSockets;
        std::map<std::string, netplus::ssl::CertificateBundle> _certBundle;
        HTTPException    _httpexception;
    };
};
