#ifndef TCPSOCKET_H
#define TCPSOCKET_H

#include <QTcpSocket>
#include <QEventLoop>
#include <QTimerEvent>

const char* socketErrKey(int value);

class TcpSocket : public QTcpSocket {
    Q_OBJECT
public:
    explicit TcpSocket(QObject *parent = nullptr) : QTcpSocket{parent} {};
    ~TcpSocket() {
        if(timerId!=0) killTimer(timerId);
    };
    bool waitForConnected(int msecs = 30000) override;
    bool waitForDisconnected(int msecs = 30000) override;
    bool waitForBytesWritten(int msecs = 30000) override;
    bool waitForReadyRead(int msecs = 30000) override;
protected:
    void timerEvent(QTimerEvent *e) override {
        if(e->timerId()!=timerId) return;
        killTimer(timerId);
        timerId = 0;
        emit timeout(5);
    };
    bool connAndExec(int msecs, QEventLoop *loop);
    inline void timerStop() {
        if(timerId==0) return;
        killTimer(timerId);
        timerId = 0;
    }
    int timerId = 0;
signals:
    void timeout(int);
};

#endif // TCPSOCKET_H
