#include "worker.h"
#include "update.h"

#include <QCoreApplication>
#include <QApplication>
#include <QDebug>
#include <QTimer>
#include <QFileInfo>
#include <QDir>
#include <QThread>

#include "message_handler.h"
#include "plugins/interfaces.h"


Worker::Worker(QString update_ctrl_file, QString workingDir)
      : m_update_ctrl_file(update_ctrl_file)
      , m_workingDir(workingDir)
      , m_workerThread("workerThread") {

    this->moveToThread(&m_workerThread);
    m_workerThread.start();
    QThread::usleep(100000);

    int cnt = 0;
    while (!m_workerThread.isRunning()) {
        if (++cnt > 5) {
            qCritical() << "starting worker thread FAILED";
            return;
        }
        QThread::sleep(1);
    }

    connect(this, SIGNAL(workNow()), this, SLOT(work()), Qt::QueuedConnection);
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(update()));
    m_timer.setSingleShot(true);
    m_timer.start(1000);
}

Worker::~Worker() {
    int cnt = 0;
    m_workerThread.quit();
    while (!m_workerThread.isFinished()) {
        if (!m_workerThread.wait(1000)) {
            if (++cnt > 5) {
                qCritical() << "stopping worker thread FAILED";
                return;
            }
        }
    }
}

void Worker::update() {
    qCritical() << __func__ << ":" << __LINE__;
    emit workNow();
}

void Worker::work() {
   qCritical() << __func__ << ":" << __LINE__;
   //Update m_update(m_update_ctrl_file, m_workingDir);
   QThread::sleep(3);
   //if (m_update.doUpdate()) {
   //}
   m_workerThread.quit();
   QApplication::quit();
}
