/*******************************************************************************
 * 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 <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:
        HttpEvent(std::vector<netplus::socket*> serversocket,int timeout = 1000);

        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};
        void _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);
        void _resumeH2Streams(HttpRequest &cureq, std::string &out,
                              const int tid, ULONG_PTR args);
    };

    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();
    protected:
        void                        FileServer();
    private:

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