#include <iostream>
#include <fstream>
#include <syncstream>
#include <string>
#include <thread>
#include <queue>
#include <future>
#include <mutex>
#include <atomic>
#include <vector>

#include "../semaphore/semaphore.h"
#include "../cmdfork/cmdfork.h"

using namespace std;

//task
using PackagedTask = packaged_task<void (string const &fname)>;

class Task
{
    string d_command;
    PackagedTask d_task;

    public:
        Task()  = default;

        Task(string const &command, PackagedTask &&tmp)
        :
            d_command(command),
            d_task(move(tmp))
        {}

        void operator()()
        {
            d_task(d_command);
            d_task.get_future();    // handles potential exceptions
        }
};
//=

class TaskQueue
{
    mutex d_mutex;
    queue<Task> d_queue;

    public:
        void push(Task &&tmp)
        {
            lock_guard<mutex> lk(d_mutex);
            d_queue.push(move(tmp));
        }

        void popFront(Task &dest)
        {
            lock_guard<mutex> lk(d_mutex);
            dest = move(d_queue.front());
            d_queue.pop();
        }

        bool empty() const
        {
            return d_queue.empty();
        }
};

extern atomic_bool g_done;
extern size_t g_sizeofWorkforce;
extern string g_marker;

extern std::vector<std::thread> g_thread;
extern fstream g_out;

extern TaskQueue g_taskQ;

extern Semaphore g_dispatcher;
extern Semaphore g_worker;


void compile(string const &line);
void jobs();
void worker();
void workforce();
string nextCommand();
void results();
