//*****************************************************************
/*
  JackTrip: A System for High-Quality Audio Network Performance
  over the Internet

  Copyright (c) 2008-2021 Juan-Pablo Caceres, Chris Chafe.
  SoundWIRE group at CCRMA, Stanford University.

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  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.
*/
//*****************************************************************

/**
 * \file UdpHubListener.h
 * \author Juan-Pablo Caceres and Chris Chafe
 * \date September 2008
 */

#ifndef __UDPHUBLISTENER_H__
#define __UDPHUBLISTENER_H__

#include <QHostAddress>
#include <QMutex>
#include <QString>
#include <QThread>
#include <QThreadPool>
#include <QUdpSocket>
#include <QVector>
#include <fstream>
#include <iostream>
#include <stdexcept>

#include "JackTrip.h"
#include "jacktrip_globals.h"
#include "jacktrip_types.h"

#ifdef WEBRTC_SUPPORT
class WebRtcPeerConnection;
#endif
#ifdef WEBTRANSPORT_SUPPORT
#include "http3/Http3Server.h"
#endif
#ifndef NO_JACK
#include "Patcher.h"
#endif
#include "Auth.h"
#include "OscServer.h"
#include "SslServer.h"

class JackTripWorker;  // forward declaration
class Settings;

/** \brief Hub UDP listener on the Server.
 *
 * This creates a server that will listen on the well know port (the server port) and will
 * spawn JackTrip threads into the Thread pool. Clients request a connection.
 */
class UdpHubListener : public QObject
{
    Q_OBJECT;

   public:
    UdpHubListener(int server_port = gServerUdpPort, int server_udp_port = 0,
                   QObject* parent = nullptr);
    virtual ~UdpHubListener();

    /// \brief Starts the TCP server
    void start();

    /// \brief Stops the execution of the Thread
    void stop() { mStopped = true; }

#ifndef NO_JACK
    void registerClientWithPatcher(QString& clientName);
    void unregisterClientWithPatcher(QString& clientName);
#endif
    int releaseThread(int id);
    void releaseDuplicateThreads(JackTripWorker* worker, uint16_t actual_peer_port);
    void getClientLatencies(QVector<QString>& clientNames, QVector<double>& latencies);
    int getBasePort() const { return mBasePort; }
    bool getConnectDefaultAudioPorts() const { return m_connectDefaultAudioPorts; }

    void setConnectDefaultAudioPorts(bool connectDefaultAudioPorts)
    {
        // Only allow us to override this in the default patching mode. (Or TUB mode.)
        //(Allows -D to continue to function as a synonym for -p5.)
        if (mHubPatch == JackTrip::SERVERTOCLIENT
            || mHubPatch == JackTrip::RESERVEDMATRIX) {
            m_connectDefaultAudioPorts = connectDefaultAudioPorts;
        }
    }

    static void sigIntHandler([[maybe_unused]] int unused)
    {
        std::cout << std::endl << "Shutting Down..." << std::endl;
        sSigInt = true;
    }

   private slots:
    void testReceive()
    {
        std::cout << "========= TEST RECEIVE SLOT ===========" << std::endl;
    }
    void receivedNewConnection();
    void stopCheck();
    void queueBufferChanged(int queueBufferSize);
    void handleLatencyRequest(const QHostAddress& sender, quint16 senderPort);
    void handleWorkerRemoval();

   signals:
    void signalStarted();
    void signalRemoveThread(int id);
    void signalStopped();
    void signalError(const QString& errorMessage);

   private:
    // new bytes are ready to read from the client connection
    void readyRead(QSslSocket* clientConnection);

    /** \brief Binds a QUdpSocket. It chooses the available (active) interface.
     * \param udpsocket a QUdpSocket
     * \param port Port number
     */
    static void bindUdpSocket(QUdpSocket& udpsocket, int port);

    int readClientUdpPort(QSslSocket* clientConnection, QString& clientName);
    int checkAuthAndReadPort(QSslSocket* clientConnection, QString& clientName);
    int sendUdpPort(QSslSocket* clientConnection, qint32 udp_port);

    void startOscServer()
    {
        // start osc server to listen to config updates
        mOscServer = new OscServer(mServerPort + 1, this);
        mOscServer->start();

        QObject::connect(mOscServer, &OscServer::signalQueueBufferChanged, this,
                         &UdpHubListener::queueBufferChanged, Qt::QueuedConnection);
        QObject::connect(mOscServer, &OscServer::signalLatencyRequested, this,
                         &UdpHubListener::handleLatencyRequest, Qt::QueuedConnection);
    };

    /**
     * \brief Send the JackTripWorker to the thread pool. This will run
     * until it's done. We still have control over the prototype class.
     * \param id Identification Number
     */
    // void sendToPoolPrototype(int id);

    /// \brief Create a new JackTripWorker and allocate it a slot
    /// \param clientName The client name (will be modified if mAppendThreadID is set)
    /// \return The slot id, or -1 if no slots available
    int createWorker(QString& clientName);

#ifdef WEBRTC_SUPPORT
    /// \brief Create a WebRTC worker for a new connection
    int createWebRtcWorker(QSslSocket* signalingSocket);
#endif

#ifdef WEBTRANSPORT_SUPPORT
    /// \brief Create a WebTransport worker for a new QUIC connection
    int createWebTransportWorker(HQUIC connection, const QHostAddress& peerAddress,
                                 quint16 peerPort);
#endif

    /** \brief Returns the ID of the client in the pool. If the client
     * is not in the pool yet, returns -1.
     */
    int getPoolID(const QString& address, uint16_t port);

    void stopAllThreads();

    // QUdpSocket mUdpHubSocket; ///< The UDP socket
    // QHostAddress mPeerAddress; ///< The Peer Address

    // JackTripWorker* mJTWorker; ///< Class that will be used as prototype
    QVector<JackTripWorker*>* mJTWorkers;  ///< Vector of JackTripWorkers
    // Pointer to OscServer
    OscServer* mOscServer;

    SslServer mTcpServer;
    int mServerPort;     //< Server known port number
    int mServerUdpPort;  //< Server udp base port number
    int mBasePort;
    // addressPortNameTriple mActiveAddress[gMaxThreads]; ///< Active address pool
    // addresses QHash<QString, uint16_t> mActiveAddressPortPair;

    bool mRequireAuth   = false;
    bool mTlsConfigured = false;
    QString mCertFile;
    QString mKeyFile;
    QString mCredsFile;
    QScopedPointer<Auth> mAuth;

    /// Boolean stop the execution of the thread
    volatile bool mStopped;
    static bool sSigInt;
    QTimer mStopCheckTimer;
    int mTotalRunningThreads;  ///< Number of Threads running in the pool
    QMutex mMutex;
    JackTrip::underrunModeT mUnderRunMode;
    AudioInterface::audioBitResolutionT mAudioBitResolution;
    int mBufferQueueLength;

    QStringList mHubPatchDescriptions;
    bool m_connectDefaultAudioPorts;
#ifndef NO_JACK
    Patcher mPatcher;
#endif
    bool mStereoUpmix;

    int mIOStatTimeout;
    QSharedPointer<std::ostream> mIOStatStream;

    int mBufferStrategy;
    int mBroadcastQueue;
    double mSimulatedLossRate;
    double mSimulatedJitterRate;
    double mSimulatedDelayRel;
    bool mUseRtUdpPriority;

#ifdef WEBRTC_SUPPORT
    /// \brief ICE servers for WebRTC connections
    QStringList mIceServers;
#endif

#ifdef WEBTRANSPORT_SUPPORT
    /// \brief QUIC/HTTP3 server lifecycle (msquic wrapper)
    Http3Server* mHttp3Server;
#endif

#ifdef WAIR  // wair
    bool mWAIR;
    void connectMesh(bool spawn);
    void enumerateRunningThreadIDs();

   public:
    void setWAIR(int b) { mWAIR = b; }
    bool isWAIR() { return mWAIR; }
#endif  // endwhere
#ifndef NO_JACK
    void connectPatch(bool spawn, const QString& clientName);
#endif

   public:
    void setRequireAuth(bool requireAuth) { mRequireAuth = requireAuth; }
    void setCertFile(const QString& certFile) { mCertFile = certFile; }
    void setKeyFile(const QString& keyFile) { mKeyFile = keyFile; }
    void setCredsFile(const QString& credsFile) { mCredsFile = credsFile; }

    unsigned int mHubPatch;
    void setHubPatch(unsigned int p)
    {
        mHubPatch = p;
#ifndef NO_JACK
        mPatcher.setPatchMode(static_cast<JackTrip::hubConnectionModeT>(p));
#endif
        // Set the correct audio port connection setting for our chosen patch mode.
        if (mHubPatch == JackTrip::SERVERTOCLIENT || mHubPatch == JackTrip::SERVFOFI
            || mHubPatch == JackTrip::SERVFULLMIX) {
            m_connectDefaultAudioPorts = true;
        } else {
            m_connectDefaultAudioPorts = false;
        }
    }
    unsigned int getHubPatch() { return mHubPatch; }

    void setStereoUpmix([[maybe_unused]] bool upmix)
    {
#ifndef NO_JACK
        mPatcher.setStereoUpmix(upmix);
#endif
    }

    void setUnderRunMode(JackTrip::underrunModeT UnderRunMode)
    {
        mUnderRunMode = UnderRunMode;
    }
    void setAudioBitResolution(AudioInterface::audioBitResolutionT AudioBitResolution)
    {
        mAudioBitResolution = AudioBitResolution;
    }
    void setBufferQueueLength(int BufferQueueLength)
    {
        mBufferQueueLength = BufferQueueLength;
    }

    void setIOStatTimeout(int timeout) { mIOStatTimeout = timeout; }
    void setIOStatStream(QSharedPointer<std::ostream> statStream)
    {
        mIOStatStream = statStream;
    }

    void setBufferStrategy(int BufferStrategy) { mBufferStrategy = BufferStrategy; }
    void setNetIssuesSimulation(double loss, double jitter, double delay_rel)
    {
        mSimulatedLossRate   = loss;
        mSimulatedJitterRate = jitter;
        mSimulatedDelayRel   = delay_rel;
    }
    void setBroadcast(int broadcast_queue) { mBroadcastQueue = broadcast_queue; }
    void setUseRtUdpPriority(bool use) { mUseRtUdpPriority = use; }
    bool mAppendThreadID = false;

#ifdef WEBRTC_SUPPORT
    /// \brief Set ICE servers for WebRTC connections
    void setIceServers(const QStringList& servers) { mIceServers = servers; }
#endif
};

#endif  //__UDPHUBLISTENER_H__
