#include "tcpclient.h"

TCPClient::TCPClient(QObject *parent) :
    QObject(parent),
    sendSystem(nullptr),
    socket(nullptr),
    recognizeSystem(nullptr),
    isConnected(false)
{
}

void TCPClient::initialize(RecognizeSystem *recognize,SendSystem *sendSystem)
{
    this->recognizeSystem = recognize;
    this->sendSystem = sendSystem;
    isConnected = false;
    emit sigSendDebugLog(Tools::getTime() + " Client started");
}

void TCPClient::setConnect(ServerSettings *serverSettings)
{
    socket = new QTcpSocket();
    qDebug() << "TCPCLient thread: " << thread();
    if (socket != nullptr && socket->state() == QTcpSocket::ConnectedState)
    {
        emit sigSendDebugLog("already connected");
        return;
    }


    socket->connectToHost(serverSettings->Address,serverSettings->Port.toShort());
    emit sigSendDebugLog("Try connect...");
    isConnected = true;

    if (socket->waitForConnected(2000))
    {
        connect(socket,&QTcpSocket::readyRead,this,&TCPClient::slotReadyRead,Qt::AutoConnection);
        connect(socket,&QTcpSocket::disconnected,this,&TCPClient::setDisconnect);

        sendSystem->setSocket(socket);
        slotConnectNotify();
    }
    else
    {
        isConnected = false;
        emit sigServerDisconnect();
    }
}

void TCPClient::setDisconnect()
{
    socket->disconnect();
    isConnected = false;
    emit sigServerDisconnect();
    emit sigSendDebugLog("Server disabled");
}

void TCPClient::slotConnectNotify()
{
    if(socket->state() != QTcpSocket::ConnectedState)
    {
        isConnected = false;
        emit sigSendDebugLog("Connect invalid");
        emit sigConnectionState(false);
    }
    else
    {
        isConnected = true;
        emit sigSendDebugLog("Connect complete");
        emit sigConnectionState(true);
        sendSystem->sendQTConnect();
    }
}

void TCPClient::slotReadyRead()
{
    if(!socket){
        emit sigSendDebugLog("WRONG SOCKET");
        return;
    }

    recognizeSystem->recognize(socket);
}

bool TCPClient::getIsConnected() const
{
    return isConnected;
}
