// Oleg Petruny staff

#include "AsyncLibrary.h"

void UAsyncLibrary::CreateAsyncTaskWithEventDelegate(FWorkDelegate workDelegate, FCallbackDelegate callback, UAsyncLibrary *&Asyncer, int execsTimes, float delayBetween, bool autoStart) {
	UAsyncLibrary *asyncer = NewObject<UAsyncLibrary>();
	asyncer->work = workDelegate;
	Asyncer = asyncer;
	asyncer->worker = new FAsyncTask<FAsyncWorker>(asyncer->work);
	asyncer->manager = new FAsyncTask<FAsyncManager>(asyncer->worker, execsTimes, delayBetween, callback);
	if (autoStart) {
		asyncer->manager->StartBackgroundTask();
	}
}

void UAsyncLibrary::CreateAsyncTaskWithFunctionName(UObject *objectWithFunction, FName functionName, FCallbackDelegate callback, UAsyncLibrary *&Asyncer, int execsTimes, float delayBetween, bool autoStart) {
	UAsyncLibrary *asyncer = NewObject<UAsyncLibrary>();
	asyncer->work.BindUFunction(objectWithFunction, functionName);
	Asyncer = asyncer;
	asyncer->worker = new FAsyncTask<FAsyncWorker>(asyncer->work);
	asyncer->manager = new FAsyncTask<FAsyncManager>(asyncer->worker, execsTimes, delayBetween, callback);
	if (autoStart) {
		asyncer->manager->StartBackgroundTask();
	}
}

void UAsyncLibrary::StartAsyncTask() {
	if (this->manager->IsIdle()) {
		this->manager->StartBackgroundTask();
	}
}

/*void UAsyncLibrary::AsyncTaskWork(int execsTimes, float delayBetween, bool execFirst, bool execLast, EAsyncExecs &Execs) {
	for (int i = 0; i < execsTimes || execsTimes == 0; i++) {
		if (execFirst && i == 0) {
			this->Task.Add(new FAsyncTask<FAsync>(this->work));
			this->Task[this->Task.Num() - 1]->GetTask().delay = delayBetween;
			this->Task[this->Task.Num() - 1]->StartBackgroundTask();
		} else if (execLast && i == execsTimes-1) {
			this->Task.Add(new FAsyncTask<FAsync>(this->work));
			this->Task[this->Task.Num() - 1]->GetTask().delay = delayBetween;
			this->Task[this->Task.Num() - 1]->StartBackgroundTask();
		} else {
			this->Task.Add(new FAsyncTask<FAsync>(this->work));
			this->Task[this->Task.Num() - 1]->GetTask().delay = delayBetween;
			this->Task[this->Task.Num() - 1]->StartBackgroundTask();
		}
	}
	Execs = EAsyncExecs::Done;
}
void UAsyncLibrary::AsyncTaskDoOnce() {
	this->Task.Add(new FAsyncTask<FAsync>(this->work));
	this->Task[this->Task.Num()-1]->StartBackgroundTask();
}*/