#include "main_window.hh"
#include "ui_main_window.h"
#include "../../TradeCore/logger.hh"


MainWindow::MainWindow(QWidget* parent):
    QMainWindow(parent), ui_(new Ui::MainWindow)
{
    ui_->setupUi(this);

    connect(
        ui_->connectButton, &QPushButton::pressed,
        this, &MainWindow::connectPressed);

    connect(
        ui_->sendButton, &QPushButton::pressed,
        this, &MainWindow::sendPressed);

    connect(
        &socket_, &QLocalSocket::connected,
        [this](){
            ui_->statusBar->showMessage(tr("Connection succesfull"));
        });

    connect(
        &socket_, static_cast<void (QLocalSocket::*)
        (QLocalSocket::LocalSocketError)>(&QLocalSocket::error),
        [this](QLocalSocket::LocalSocketError){
            ui_->statusBar->showMessage(socket_.errorString());
        });

    connect(
        &socket_, &QLocalSocket::bytesWritten,
        [this](qint64 bytes){
            ui_->statusBar->showMessage(
                tr("Written ") + QString::number(bytes) + tr(" bytes"));
        });

    connect(
        &socket_, &QLocalSocket::readyRead,
        this, &MainWindow::readData);

    connect(
        &socket_, &QLocalSocket::disconnected,
        [this](){
            ui_->statusBar->showMessage(tr("Disconnected from server"));
        });
}

void MainWindow::connectPressed()
{
    ui_->statusBar->showMessage(tr("Connecting ..."));
    socket_.connectToServer(ui_->serverName->text());
}

void MainWindow::sendPressed()
{       
    if (!socket_.isOpen()) {
        ui_->statusBar->showMessage(tr("Device not opened"));
        return;
    }

    QByteArray block;
    QDataStream stream(&block, QIODevice::WriteOnly);
    stream.setVersion(QDataStream::Qt_5_0);

    stream << (quint16)0;
    stream << ui_->requestEdit->toPlainText().toLatin1();
    stream.device()->seek(0);
    stream << (quint16)(block.size() - sizeof(quint16));

    socket_.write(block);
    socket_.flush();

    ui_->statusBar->showMessage(tr("Data sent"));
}

void MainWindow::readData()
{
    socket_.blockSignals(true);

    quint16 bytesToRead = 0;
    {
        QDataStream stream(&socket_);
        stream.setVersion(QDataStream::Qt_5_0);
        stream >> bytesToRead;
    }

    QByteArray block;
    block.append(socket_.readAll());

    while(socket_.waitForReadyRead(0))
        block.append(socket_.readAll());

    QString messageText;
    {
        QDataStream stream(&block, QIODevice::ReadOnly);
        stream.setVersion(QDataStream::Qt_5_0);
        QByteArray data;
        stream >> data;
        messageText = QString::fromLatin1(data);
    }

    socket_.blockSignals(false);
    ui_->responseEdit->setPlainText(messageText);
}

MainWindow::~MainWindow()
{
    delete ui_;
}
