#include "Async.h"

// A modular function that allows me to start a new async 
void StartAsync(std::atomic<bool>& bCancelFlag, std::future<void>& async, std::function<void(const std::atomic<bool>&)> task)
{
    // Sets the cancel flag that is called to false
    bCancelFlag.store(false);
    // Sets the new async task. Sets the cancel flag to that also
    async = std::async(std::launch::async, task, std::ref(bCancelFlag));
}

// I am using this because if the thread is sleeping and I try to cancel it using a flag, it has to wait as long as is inputted. This way I can check every second if the program wants to cancel the async function
// Custom sleep function that checks the stop flag
void ThreadSleep(const std::atomic<bool>& bCancelFlag, const int secondsSleep)
{
    for (int i = 0; i < secondsSleep; ++i)
    {
        // Checks if the flag is true if so it will finish this function if not it will sleep for 1 second and continue until secondsSleep condition is met
        // This is because sleep(1000) from windows api would not let the async functions end until the program resumed
        if (bCancelFlag.load())
        {
            return;
        }

        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}
