#include "tcpsocket.h"
#include <QEventLoop>
#include <QMetaEnum>

const char* socketErrKey(int value) {
    static auto metaEnum = QMetaEnum::fromType<QAbstractSocket::SocketError>();
    return metaEnum.valueToKey(value);
}

bool TcpSocket::waitForConnected(int msecs) {
    if(state() == ConnectedState) return true;
    QEventLoop loop;
    connect(this, &QTcpSocket::connected, &loop, &QEventLoop::quit);
    return connAndExec(msecs, &loop);
}
bool TcpSocket::waitForDisconnected(int msecs) {
    if(state() == UnconnectedState) return true;
    QEventLoop loop;
    connect(this, &QTcpSocket::disconnected, &loop, &QEventLoop::quit);
    return connAndExec(msecs, &loop);
}
bool TcpSocket::waitForBytesWritten(int msecs) {
    QEventLoop loop;
    connect(this, &QTcpSocket::bytesWritten, &loop, &QEventLoop::quit);
    return connAndExec(msecs, &loop);
}
bool TcpSocket::waitForReadyRead(int msecs) {
    QEventLoop loop;
    connect(this, &QTcpSocket::readyRead, &loop, &QEventLoop::quit);
    return connAndExec(msecs, &loop);
}

bool TcpSocket::connAndExec(int msecs, QEventLoop *loop) {
    connect(this, &QTcpSocket::errorOccurred, loop, [loop] {
        loop->exit(1);
    });
    if(msecs > 0) {
        connect(this, &TcpSocket::timeout, loop, &QEventLoop::exit);
        if(timerId!=0) killTimer(timerId);
        timerId = startTimer(msecs);
    }
    auto res = loop->exec();
    timerStop();
    if(res==5) setSocketError(SocketTimeoutError);
    return res==0;
}
