#include "OneThread.h"
#include <QDebug>
#include <QCoreApplication>

OneThread::OneThread(QThread* thread, QObject* parent) : QObject(parent), m_thread(thread)
{
    /* 将自身移动到子线程中去 */
    this->moveToThread(m_thread);


    /* 指定为队列连接 */
    connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection);
    /* 注册数据类型 */
    qRegisterMetaType<std::function<int(void)>>("std::function<int(void)>");
    qRegisterMetaType<std::function<void(void)> >("std::function<void(void)>");
    /* 连接信号和槽 */
    connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask);
    connect(this, &OneThread::signal_runTaskRunOne, this, &OneThread::do_runTaskRunOne);
}

OneThread::OneThread(QObject* parent) : QObject(parent)
{
    m_thread = new QThread();
    /* 将自身移动到子线程中去 */
    this->moveToThread(m_thread);
    /* 指定为队列连接 */
    connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection);
    /* 注册数据类型 */
    qRegisterMetaType<std::function<int(void)>>("std::function<int(void)>");
    qRegisterMetaType<std::function<void(void)> >("std::function<void(void)>");
    /* 连接信号和槽 */
    connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask);
    connect(this, &OneThread::signal_runTaskRunOne, this, &OneThread::do_runTaskRunOne);
}

OneThread::~OneThread()
{
    if(m_thread != nullptr)
    {
        m_thread->quit();
        m_thread->wait();
        // delete m_thread;
        m_thread = nullptr;
    }
}


/* 传入函数,运行函数 */
void OneThread::do_runTask(std::function<void(void)> func)
{
    qDebug() << "----- do_runTask , Thread ID: " << QThread::currentThreadId();
    m_threadRunning = true;
    while(m_threadRunning)
    {
        func();
        /* 进入事件循环 */
        QCoreApplication::processEvents();
        /* 延时1ms */
        QThread::usleep(100);
    }
    qDebug() << "----- do_runTask end -----";
}

void OneThread::do_runTaskRunOne(std::function<void(void)> func)
{
    func();
}