#include "MTcpServer.h"
#include <QDebug>
#include <QTcpSocket>

MTcpServer::MTcpServer(QObject* parent)
    : QTcpServer { parent }
{
}

void MTcpServer::setMsgHandle(MsgHandle handle)
{
    m_handle = handle;
}

bool MTcpServer::startServer(quint16 port)
{
    if (isListening() && serverPort() == port) {
        qDebug() << Q_FUNC_INFO << "start server" << port;
        return true;
    }
    close();
    if (listen(QHostAddress::Any, port) == false) {
        qDebug() << Q_FUNC_INFO << "listen error" << port << errorString();
        return false;
    }

    qDebug() << Q_FUNC_INFO << "start server" << port;
    return true;
}

void MTcpServer::sendData(const QString& data, const QString& id)
{
    if (id == "broadcast") {
        for (auto it = m_connections.begin(); it != m_connections.end(); it++)
            emit it.value()->sendData(data);
    }
    if (m_connections.contains(id))
        emit m_connections.value(id)->sendData(data);
}

void MTcpServer::incomingConnection(qintptr handle)
{
    MTcpSocketControl* control = new MTcpSocketControl(m_handle);
    connect(control, &MTcpSocketControl::recvData, [this, handle](const QString& data) {
        emit this->recvData(QString::number(handle), data);
        //  qDebug() <<QString::number(handle) <<data;
    });
    connect(control, &MTcpSocketControl::sendFail, [this, handle]() {
        m_connections.remove(QString::number(handle));
    });

    emit control->initSocket(handle);
    QSharedPointer<MTcpSocketControl> p(control);
    m_connections[QString::number(handle)] = p;
}
