#include <iostream>
#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;

struct Result
{
    bool ok;
    string display;
};

//task
using PackagedTask = packaged_task<Result (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);
        }

        shared_future<Result> result()
        {
            return d_task.get_future().share();
        }
};
//=

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 size_t g_sizeofWorkforce;
extern atomic_bool g_done;

extern vector<thread> g_thread;
extern TaskQueue g_taskQ;

extern queue<shared_future<Result>> g_resultQ;
extern mutex g_resultQMutex;

extern Semaphore g_dispatcher;
extern Semaphore g_worker;


Result compile(string const &line);
void jobs();
bool newResult(Result &result);
void newTask(string const &line);
void pushResultQ(shared_future<Result> const &sharedResult);
void results();
void worker();
void workforce();
string nextCommand();
