#include "websocketserver.h"
#include <QFile>
#include <QtWebSockets/QWebSocket>
#include <QtWebSockets/QWebSocketServer>

QT_USE_NAMESPACE

WebsocketServer::WebsocketServer(QObject *parent) : QObject(parent),m_pWebSocketServer(nullptr)
{
    m_pWebSocketServer = new QWebSocketServer(QStringLiteral("WebSocket Server"),QWebSocketServer::NonSecureMode,this);
    connect(m_pWebSocketServer,&QWebSocketServer::newConnection,this,&WebsocketServer::onNewConnection);

    if(!m_pWebSocketServer->listen(QHostAddress::Any,51213)){
        printf("WebSocketServer listen failed\n");
        exit(1);
    }
    printf("WebSocketServer listen success\n");
}

WebsocketServer::~WebsocketServer()
{
    m_pWebSocketServer->close();

    m_clients.clear();
}

void WebsocketServer::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();

    WebsocketClient *client = new WebsocketClient(pSocket,this);
    connect(client,&WebsocketClient::closed,this,&WebsocketServer::socketDisconnected);
    m_clients.append(client);
}

void WebsocketServer::socketDisconnected()
{
    WebsocketClient *pclient = qobject_cast<WebsocketClient*>(sender());
    if(pclient)
    {
        m_clients.removeAll(pclient);
    }

}
