#include "TcpClient.h"

TcpClient::TcpClient(const QString& ip, qint16 port, QObject* parent)
    : QObject(parent)
    , m_ip(ip)
    , m_port(port)
{
    m_socket = new QTcpSocket();
    m_socket->connectToHost(ip, port);
}

TcpClient::~TcpClient()
{
    releaseSocket();
}

void TcpClient::releaseSocket()
{
    if (m_socket) {
        m_socket->close();
        delete m_socket;
        m_socket = nullptr;
    }
}

bool TcpClient::sendData(const char* data)
{
    if (!m_socket->isOpen()) {
        m_socket->connectToHost(m_ip, m_port);
        if (!m_socket->isOpen()) {
            return false;
        }
    }
    qint64 sendRe = m_socket->write(data, strlen(data));
    if (-1 == sendRe) {
        qDebug() << Q_FUNC_INFO << " error : sendRe is -1, data :" << data;
        return false;
    }
    if (sendRe != qint64(strlen(data))) {
        qDebug() << Q_FUNC_INFO << " error : sendRe != strlen(data), data :" << data;
        return false;
    }
    if (!m_socket->waitForBytesWritten()) {
        qDebug() << Q_FUNC_INFO << " error : sendRe waitForBytesWritten false , data :" << data << m_socket->errorString();
        return false;
    }
    qDebug() << Q_FUNC_INFO << " is : " << data;
    return true;
}

bool TcpClient::isConnect()
{
    return m_socket->isWritable();
}
