#include "pch.h"
#include "Concurrent.h"
#include <QDebug>

Concurrent::Concurrent()
{
}

Concurrent::~Concurrent()
{
	reset();
}

void Concurrent::start()
{
	qDebug() << "Hello Start";
	if (thread != nullptr) reset();
	qDebug() << "Start after reset";
	thread = new std::thread(&Concurrent::run, this);
	qDebug() << "Start end";
}

void Concurrent::pause()
{
	paused = !paused;
	cv.notify_one();
}

void Concurrent::reset()
{
	qDebug() << "Hello Reset";
	cancel = true;
	paused = false;
	cv.notify_one();
	if (thread != nullptr) {
		thread->join();
		delete thread;
		thread = nullptr;
	}
	cancel = false;
}



void Concurrent::run()
{
	for (;false;) {
		checkPaused();
		if (checkCancel()) { break; }
	}
}

bool Concurrent::checkCancel()
{
	return cancel;
}

void Concurrent::checkPaused()
{
	std::unique_lock<std::mutex> lck(mutex);
	while (paused) {
		qDebug() << "while";
		cv.wait(lck);
	}
}
