#include "requestfromserver.h"
#include "ui_requestfromserver.h"
#include <QDebug>
#include <QPushButton>

Q_DECLARE_METATYPE( std::vector< std::vector< cv::Point > >* )

RequestFromServerThread::RequestFromServerThread(QString serverAddress, Frame *f)
    : QThread(),
      serverAddress( serverAddress ),
      f( f )
{
    this->client = 0;
    this->setTerminationEnabled();
}

// Fragt die Daten vom Server ab
void RequestFromServerThread::run()
{
    try {
        DetectionClient client;
        this->client = &client;
        this->setTerminationEnabled();
        client.connect( serverAddress.toStdString() );
        std::vector< std::vector< cv::Point > > *objects = client.getContours( f->getImageMatrix() );
        QThread::sleep(1);
        threadReady( objects );
        this->client = 0;
        return;
    }
    catch( ... )
    {
        qDebug() << "no connection to Server";
    }
    QThread::sleep(1);
    threadReady( new std::vector< std::vector< cv::Point > >() );
    this->client = 0;
}

// Inhalt der RequestFromServer Klasse
//-------------------------------------

RequestFromServer::RequestFromServer(QString serverAddress, Frame *f, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RequestFromServer),
    rfst( new RequestFromServerThread( serverAddress, f ) )
{
    ui->setupUi(this);
    connect(rfst, &RequestFromServerThread::threadReady, this, &RequestFromServer::onThreadReady);
    rfst->start();

}

RequestFromServer::~RequestFromServer()
{
    delete rfst;
    delete ui;
}

std::vector< std::vector< cv::Point > > RequestFromServer::getObjects()
{
    return objects;
}

// Abfragen von Vorabannotationen abbrechen
void RequestFromServer::on_abbrechen_clicked()
{
    disconnect(rfst, &RequestFromServerThread::threadReady, this, &RequestFromServer::onThreadReady);
    qDebug() << "disconnected";
    ui->label->setText( "Vorgang wird abgebrochen..." );
    if( rfst->client )
        rfst->client->cancel = 1;
    rfst->wait();
    this->close();
}

// Abfragen von Vorabannotationen abgeschlossen
void RequestFromServer::onThreadReady( std::vector< std::vector< cv::Point > > *objects )
{
    qDebug() << "onThreadReady";
    ui->abbrechen->setEnabled( false );
    this->objects = *objects;
    delete objects;
    this->close();
}
