#include "tcpclient.h"
#include "Core/updatecontroller.h"
#include "externalexecuter.h"

#include <QDir>

TCPClient::TCPClient(QObject *parent) :
    QObject(parent)
{

}

void TCPClient::Initialize(RecognizeSystem *recognize,ExternalExecuter *externalExecuter)
{
    this->recognizeSystem = recognize;
    this->externalExecuter = externalExecuter;

    emit onSendDebugLog(Tools::GetTime() + " Client started");
}

void TCPClient::SetConnect(ServerSettings *serverSettings)
{
    socket = new QTcpSocket(this);

    connect(socket,&QTcpSocket::readyRead,this,&TCPClient::onReadyRead,Qt::DirectConnection);
    connect(socket,&QTcpSocket::disconnected,this,&TCPClient::SetDisconnect);
    connect(this,&TCPClient::Recognize,recognizeSystem,&RecognizeSystem::Recognize,Qt::DirectConnection);

    socket->connectToHost(serverSettings->Address,serverSettings->Port.toShort());
    emit onSendDebugLog("Try connect...");

    socket->waitForReadyRead();

    if(socket->state() != QTcpSocket::ConnectedState){
        emit onSendDebugLog("Connect invalid");
        emit ConnectionState(false);
        return;
    }else{
        emit onSendDebugLog("Connect complete");
        emit ConnectionState(true);
    }
}

void TCPClient::SendClientAutorization()
{
    QDataStream stream(socket);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);

    if(socket->state() != QTcpSocket::ConnectedState){
        emit ConnectionState(false);
        return;
    }

    QFile file(tempName);
    file.open(QIODevice::ReadOnly);

    QByteArray array = file.readAll();
    stream << PacketType::TYPE_XMLANSWER;
    stream << array;
    socket->waitForBytesWritten();
}

void TCPClient::SendFile()
{
    QDataStream stream(socket);
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);
    quint64 fileSize = 0;
    int countSend = 0;

    QFile file(hashFilename);       //Открываем файл для чтения

    stream << PacketType::TYPE_FILE; //Отправляем тип блока
    QFileInfo fileInfo(file);

    fileSize = fileInfo.size();
    stream << fileSize;

    if(file.open(QFile::ReadOnly | QFile::Text)){
        while(!file.atEnd()){
            QByteArray data = file.readAll();//file.read(1025*250);
            stream << data;
            countSend++;
        }

        qDebug() << Tools::GetTime() << "count end Final: " << countSend;
    }

    file.close();

    qDebug() << "Transaction after send file: " << socket->isTransactionStarted();
    countSend = 0;
}

void TCPClient::SetDisconnect()
{
    socket->disconnect();
    emit onSendDebugLog("Server disabled");
}

void TCPClient::WaitWrites()
{
    socket->waitForBytesWritten();
}

void TCPClient::WaitRead(int time)
{
    socket->waitForReadyRead(time);
}

QTcpSocket *TCPClient::GetSocket()
{
    return socket;
}

void TCPClient::MessageEntered(QString message)
{
    QDataStream stream(socket);
    QByteArray data;
    stream.setVersion(QDataStream::Qt_DefaultCompiledVersion);

    if(!message.isEmpty() && socket->state() == QTcpSocket::ConnectedState){

        if(message == "check")
        {
            stream << PacketType::TYPE_COMMAND;
            stream << message;
            socket->waitForBytesWritten();

            SendFile();
            emit onSendDebugLog(Tools::GetTime() + " Local checkFile sended");

            socket->waitForReadyRead(1000);
        }
        else if(message == "update"){
            emit onSendDebugLog("Update started");
            stream << PacketType::TYPE_COMMAND;
            stream << message;
            socket->waitForBytesWritten();
        }
        else if(message == "run"){
            externalExecuter->CallApp();
        }
    }else{
        emit onSendDebugLog("WRONG SOCKET AFTER ENTERED");
    }
}

void TCPClient::onReadyRead()
{
    if(!socket){
        emit onSendDebugLog("WRONG SOCKET");
        return;
    }
//    qDebug() << "Transaction before recognize: " << socket->isTransactionStarted();

//    if(socket->isTransactionStarted()) return;

    emit Recognize(socket);
}

TCPClient::~TCPClient()
{

}
