#include "SignalServer.h"
#include "../Application.h"
#include "Core/Logger.h"
#include "HttpServer/HttpSession.h"
#include "WebSocketSignalSession.h"
#include <boost/beast/websocket/rfc6455.hpp>

namespace Danki {
SignalServer::SignalServer(Application &app) {
    using namespace boost::urls;
    // clang-format off
    app.insertUrl("/api/v1/webrtc/signal/{id}", [this](HttpSession &session, const Application::Request &request, const matches &matches) {
        auto id = matches.at("id");
        if (boost::beast::websocket::is_upgrade(request)) {
            auto ws = std::make_shared<WebSocketSignalSession>(session.releaseSocket(), *this, id);
            ws->run(request);
        } else {
            LOG(error) << "webrtc client[" << id << "] not upgrade connection, request: " << std::endl << request;
        }
    });
    // clang-format on
}

void SignalServer::join(const std::string &id, WebSocketSignalSession *client) {
    m_clients.insert({id, client});
}

void SignalServer::leave(const std::string &id) {
    if (m_clients.count(id) > 0) {
        m_clients.erase(id);
    }
}

WebSocketSignalSession *SignalServer::client(const std::string &id) {
    WebSocketSignalSession *ret = nullptr;
    if (m_clients.count(id) > 0) {
        ret = m_clients.at(id);
    }
    return ret;
}
} // namespace Danki